File
- file.mkDir()和file.mkDirs()的区别:当创建的文件夹父目录存在时,二者相同,不存在时必须使用mkDirs()
- FileFilter和FilenameFilter的使用,用于遍历一个文件夹中所有文件,限定要显示的文件的条件
流
概念图
- InputStream和Outputstream都是抽象类,只能由子类来实例化
代码示例
package filetest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class MyFile {
public static void main(String[] args) {
File file=new File("E:\\11.txt");
try {
InputStream is=new FileInputStream(file);
//每次读取bb.length个字节的长度的数据,相当于定义了一个桶
byte[] bb=new byte[4];
int b=is.read(bb);
while (b!=-1) {
//String(byte[] byte,int offset,int length) String的构造方法
System.out.print(new String(bb,0,b));
b=is.read(bb);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IO流分类
- 字符流InputStream OutputStream
- 字符流 Reader Writer
- 字符缓冲流 BufferedReader BufferedWriter
- 标准输出流 PrintStream PrintWriter
RandomAccessFile类
- RandomAccessFile 从文件的某一个位置开始读或者写
- seek(long pos) 将虚拟的光标定位到pos位置
- public RandomAccessFile(File file,String mode)构造函数 ,mode 参数指定用以打开文件的访问模式。允许的值及其含意为:
- ”r” 以只读方式打开,
- ”rw” 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
XML文件解析
XML文件构成
- xml文件 html 标签 内容
- XML文件的声明,声明了版本号和编码格式
- 书写示例
<?xml version="1.0" encoding="UTF-8"?>
<class>
<student>
<name>张三</name>
<age>19</age>
<sex>男</sex>
</student>
<student>
<name>李四</name>
<age>21</age>
<sex>女</sex>
</student>
<student>
<name>王五</name>
<age>20</age>
<sex>男</sex>
</student>
<student>
<name>赵六</name>
<age>23</age>
<sex>女</sex>
</student> <!--这是注释语句哦-->
</class>
- xml文件优点
- 简单性 灵活性 独立于平台 独立于语言 可扩展性
- 作用:数据存储 数据交换 数据配置
DOM解析XML文件
- DOM 将xml文件映射成倒挂的树,读取到内存中,xml文件不要大于10M
- 1.Xml解析器工厂 DocumentBuilderFactory抽象类 newInstance();实例化
- 2.Xml解析器 DocumentBuilder实例化
- 3.使用xml解析器将xml文件映射成DOM倒挂树(Document)
Document实例化parse(File file);file的文件路径即为xml文件 - 4.使用Document对xml文件进行解析
NodeList list=document.getElementsByTagName
package day18IO;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLTest {
public static void main(String[] args) {
// Xml解析器工厂实例化
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
// Xml解析器实例化
DocumentBuilder builder = factory.newDocumentBuilder();
// 使用xml解析器将xml文件映射成DOM倒挂树,Document对象实例化 注意:是parse(File file)方法
Document document = builder.parse("XMLTest.xml");
// 获取element对象nodelist,也就是student的nodelist
NodeList list = document.getElementsByTagName("student");
ArrayList<Student> students = new ArrayList<Student>();
for (int i = 0; i < list.getLength(); i++) {
// 拿出第一个element对象,也就是第i个student
Node node = list.item(i);
Student stu = new Student();
// 获取node的第一个子节点,也就是student的第一个子节点
Node child = node.getFirstChild();
while (child != null) {
// System.out.println("节点名称"+child.getNodeName()+"节点值"+child.getNodeValue()+"节点类型"+child.getNodeType());
// 如果child的节点类型是ELEMENT_NODE类型的话,表示不是包含子内容
if (child.getNodeType() == Node.ELEMENT_NODE) {
// 获取子内容的值
String str = child.getFirstChild().getNodeValue();
// 判断值的内容,在进行对Student对象的赋值
if (child.getNodeName().equals("name")) {
stu.setName(str);
} else if (child.getNodeName().equals("age")) {
stu.setAge(str);
} else {
stu.setSex(str);
}
System.out.println(str);
}
// 将child指向下一个子节点
child = child.getNextSibling();
}
// 将student对象添加到Students的list中
students.add(stu);
}
System.out.println("**************************************");
for (int i = 0; i < students.size(); i++) {
System.out.println("姓名:" + students.get(i).getName());
System.out.println("年龄:" + students.get(i).getAge());
System.out.println("性别:" + students.get(i).getSex());
System.out.println();
}
System.out.println("**************************************");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Node对象的getFirstChild()方法和getNextSibling()方法的区别
- getFirstChild()方法仅限于获取第一个子节点
- getNextSibling()方法用于获取后续节点
SAX解析XML
- SAX是通过事件来进行解析xml文件的
- 用SAX解析XML文件,必须写一个类继承XML,重写其中的startDocument(),endDocument(),startElement(String arg0, String arg1, String arg2,
Attributes arg3),endElement(String arg0, String arg1, String arg2),characters(char[] arg0, int arg1, int arg2)五个方法
public class SAXTest {
public static void main(String[] args) {
//创建SAXParserFactory解析器工厂
SAXParserFactory factory=SAXParserFactory.newInstance();
try {
//通过解析器工厂创建SAXParser解析器
SAXParser parser=factory.newSAXParser();
parser.parse("XMLTest.xml", new Handler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MyHandler extends DefaultHandler{
private ArrayList<Student> clazz;
private Student student;
private String tagName;
@Override
public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
super.characters(arg0, arg1, arg2);
String value=new String(arg0,arg1,arg2);
//对标签名称进行匹配,如果匹配成功,则对相应的student属性进行赋值
if ("name".equals(tagName)) {
student.setName(value);
}else if ("age".equals(tagName)) {
student.setAge(value);
}else if("sex".equals(tagName)){
student.setSex(value);
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("解析文档结束");
for (Student s: clazz) {
System.out.println(s);
}
}
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException {
super.endElement(arg0, arg1, arg2);
//在结束标签中,将记录标签名称的全局变量置空,可用于避免结束标签执行时,将结束标签的内容进行赋值给student的属性,导致输出内容时不正确
tagName=null;
//在结束标签时判断标签内容是否是student,如果是,则将该student对象添加到clazz中
if (arg2.equals("student")) {
clazz.add(student);
}
System.out.println("解析标签结束"+arg2);
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
System.out.println("解析文档开始");
//解析文档开始时,将clazz进行初始化
clazz=new ArrayList<Student>();
}
@Override
public void startElement(String arg0, String arg1, String arg2,
Attributes arg3) throws SAXException {
super.startElement(arg0, arg1, arg2, arg3);
System.out.println("解析标签开始"+arg2);
//解析标签时,对标签内容进行判断,如果是student那么就将student实例化
if (arg2.equals("student")) {
student=new Student();
System.out.println("***************************");
System.out.println(arg3.getValue("num"));
System.out.println("***************************");
}
//记录下每次开始标签的标签名称
tagName=arg2;
}
}
public class Student {
private String name;
private String age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "姓名:"+getName()+" 年龄:"+getAge()+" 性别:"+getSex();
}
}
JSON
- JSON解析需要导入第三方的jar包,方法:右键项目–>Build Path–>Add External Archiver…
public class JsonTest {
public static void main(String[] args) {
/**
* 生成Json
*/
//生成JsonObject对象
JSONObject object=new JSONObject();
//向其中添加String内容
object.accumulate("clazzName", "一年级二班");
//生成JsonArray对象
JSONArray students=new JSONArray();
Student zhangsan=new Student("张三", "18", "男");
Student lisi=new Student("李四", "23", "女");
Student wangwu=new Student("王五", "10", "男");
Student zhaoliu=new Student("赵六", "30", "女");
//向JsonArray对象中添加数据
students.add(zhangsan);
students.add(lisi);
students.add(wangwu);
students.add(zhaoliu);
//将JsonArray对象添加到最初的JsonObject对象中
object.accumulate("clazz", students);
//输出生成的Json的内容
System.out.println(object.toString());
/**
* 解析Json
*/
//将Json文件中的内容全部读取出来,存放在字符串中
try {
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("myjson")));
String str="";
String line=br.readLine();
while (line!=null) {
str+=line;
line=br.readLine();
}
//读取Json文件,并获取Json的object
JSONObject object2=JSONObject.fromObject(str);
System.out.println(object2.getString("clazzName"));
System.out.println();
//获取jsonobject中的jsonarray对象
JSONArray students2=object2.getJSONArray("clazz");
//遍历jsonarray对象中的所有jsonobject元素,获取并输出其值
for (int i = 0; i < students2.size(); i++) {
JSONObject student=students2.getJSONObject(i);
System.out.println(student.getString("name"));
System.out.println(student.getString("age"));
System.out.println(student.getString("sex"));
System.out.println();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}