打印流
- 自动换行: 调用println();
- 自动刷新: 特定的构造方法和调用println()等方法;
1.字符打印流
- PrintWriter(String fileName)
(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))
- PrintWriter(File file)
new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))public
- PrintWriter(OutputStream out)
(new BufferedWriter(new OutputStreamWriter(out))
- PrintStream(OutputStream out, boolean autoFlush --> 打开自动刷新
复制文本
BufferedReader br = new BufferedReader(new FileReader("file_1.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("file_2.txt",true),true);
String str;
while ((str = br.readLine()) != null) {
pw.println(str);
}
br.close();
pw.close();
2.字节打印流
- printStream为OutputStream的子类,用于输出信息到命令行;
- public static PrintStream out
- PrintStream --> OutputStream(子类) 引用类型;
- out --> 参数;
- OutputStream os = System.out;
- System.out.print (“字节输出流”);
对象操作流
- 对象输出输入流是并套使用,用对象输入读取对象,用对象输出流输出对象;
对象输出流
- 构造函数: new ObjectOutputStream (new FileOutputsream(“a.txt”));
- writeObject(Object o);
main()
OutputStream os = new FileOutputStream("file.txt");
ObjectOutputStream oos = new ObjectOutputStream(os);
Student s1 = new Student("zhangsan",17);
Student s2 = new Student("zhangsi",18);
oos.writeObject(s1);
oos.writeObject(s2);
oos.close();
- 将对象封装到ArrayList进行输出,方便输出时的调用;
ArrayList<Student> als = new ArrayList<Student>();
als.add(new Student("A",12));
als.add(new Student("B",31));
- 实现对象操作流的学生类必须实现Serializable,Serializable接口没有方法,起到标识作用,说明该对象实现对象操作流;
- 使用不当会抛出InvalidClassException
- 原因:
- 该类的序列版本号与从流中读取的类描述符的版本号不匹配: 对象类成员发生改变,输出输入文件未改变,此时序列号版本便不匹配;
- 该类包含未知数据类型
- 该类没有可访问的无参数构造方法
- 对象类要自定义序列号
public class Student implements Serializable {
private static final long serialVersionUID = -1390205995143526463L;
}
public class Student implements Serializable {
private String name;
private int age;
}
对象输入流
- 构造方法 :ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“file.txt”));
- readObject(Object o),调用时会抛出ClassNotFoundException;
- 当文本对象全部读取时,jvm便会抛出EOFException,同try…catch()处理异常;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.txt"));
try {
while(true) {
Object o = ois.readObject();
System.out.println(o);
}
} catch (EOFException e) {
System.out.println("读取完毕!!");
}
ois.close();
}
- 将对象用ArrayList封装成对象数组,便于输入时遍历;
- ArrayList alss = ( ArrayList)o;//向下转型;
Object o = ois.readObject();
System.out.println(o);
ArrayList<Student> alss = ( ArrayList<Student>)o;
for (Student s : alss) {
System.out.println(s);
}