由于FileInputStream和FileOutputStream使用的不方便
所以使用包装类将数据转换传递到OutputStream,
因为包装类是对节点流操作所以构造函数需要参数
DateOutputStream(OutputStream fos); 分层
缓冲流为IO增加缓冲区提高程序效率 BefferedOutputStream 缓冲区默认为32个字节 可以在构造是定义大小 最好为整合倍
利用BufferedOutputStream 的 newLine()方法 在不同平台上换行十分方便
读取时由与不知道结尾的位置所以只有 readUTF方法
-----------------------------------------------------------------------------------------------------
↗ DateOutputStream → BufferedOutputStream → FileOutputStream ↘
程序 文件
↖ DateInputStream ← BufferedInputStream ← FileInputStream ↙
------------------------------------------------------------------------------------------------------
流进行分层 提高程序 读写
ObjectInputStream 对象必须实现Serializable接口 使其可序列化
Reader Writer类似 ,并且读取一行readLine();
测试结果:
******************************************
id:258 name:一号 age23
id:23 name:二号 age24
******************************************
import java.io.*;
public class TestSeralizable {
public static void main(String[] args) throws Exception{
Student1 s1 = new Student1(258,"一号",23);
Student1 s2 = new Student1(23,"二号",24);
File fin = new File("Student.txt");
if(!fin.exists()){
fin.createNewFile();
}
FileOutputStream out = new FileOutputStream(fin);
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(s1);
oout.writeObject(s2);
oout.close();
FileInputStream in = new FileInputStream(fin);
ObjectInputStream oin = new ObjectInputStream(in);
Student1 news1 = (Student1)oin.readObject();
Student1 news2 = (Student1)oin.readObject();
System.out.println(news1);
System.out.println(news2);
}
}
class Student1 implements Serializable{
int id;
String name;
int age;
public Student1(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String toString(){
return "id:"+this.id+" name:"+this.name+" age"+this.age;
}
}
import java.io.*;
public class TestBuffered {
public static void main(String[] args) throws Exception{
File fin = new File("Buffered.txt");
if(!fin.exists()){
fin.createNewFile();
}
FileInputStream in = new FileInputStream(fin);
FileOutputStream out = new FileOutputStream(fin);
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(out);
DataInputStream dis = new DataInputStream(bis);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF("ab中国");
dos.flush();
dos.close();
//dos.writeChars("char中国");
String str = dis.readUTF();
System.out.println(str);
}
}