序列化流
- 高级流
- 需要依托低级流
- ObjectOutputStream
- ObjectInputStream
ObjectOutputStream
-
将java对象写入文件
-
基本用法
@Test public void objectOutputStreamTest(){ try { FileOutputStream outputStream = new FileOutputStream("E:/ObjectOutputStreamTest.txt"); //使用低级流初始化ObjectOutputStream ObjectOutputStream oos = new ObjectOutputStream(outputStream); //将对象写入文件中(注:该类必须实现Serializable接口) oos.writeObject(new Student("赵玉龙", 3)); //释放资源 oos.close(); } catch (IOException e) { e.printStackTrace(); } }
ObjectInputStream
-
从从文件中读取java对象
-
基本用法
@Test public void objectInputStreamTest(){ try { FileInputStream inputStream = new FileInputStream("E:/ObjectOutputStreamTest.txt"); //使用低级流初始化ObjectInputStream ObjectInputStream ois = new ObjectInputStream(inputStream); Student student = (Student) ois.readObject(); ois.close(); System.out.println(student); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }
案例:将java对象写入文件后读取它
@Test
public void writeObjects(){
//实例化一组java对象
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 3));
students.add(new Student("李四", 3));
students.add(new Student("王五", 3));
try {
//实例化一个ObjectOutputStream对象用来写
FileOutputStream outputStream = new FileOutputStream("E:/writeObjects.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//将一组java对象放到List中后写入文件
objectOutputStream.writeObject(students);
objectOutputStream.close();
//实例化一个ObjectInputStream对象用来读
FileInputStream inputStream = new FileInputStream("E:/writeObjects.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
//从文件中将之前写入的List读取到一个新的List对象中
List<Student> studentList = new ArrayList<>();
studentList = (List<Student>) objectInputStream.readObject();
System.out.println(studentList);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}