diff --git a/s-day10/src/com/inmind/object_stream03/Test11.java b/s-day10/src/com/inmind/object_stream03/Test11.java new file mode 100644 index 0000000..a4f69ca --- /dev/null +++ b/s-day10/src/com/inmind/object_stream03/Test11.java @@ -0,0 +1,38 @@ +package com.inmind.object_stream03; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; + +/* +序列化流的练习 + +需求: +1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。 +2. 反序列化list.txt ,并遍历集合,打印对象信息。 + */ +public class Test11 { + public static void main(String[] args) throws Exception { + //1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。 + ArrayList lists = new ArrayList<>(); + lists.add(new Student("张三1", 18)); + lists.add(new Student("张三2", 19)); + lists.add(new Student("张三3", 20)); + lists.add(new Student("张三4", 21)); + + ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt")); + oos.writeObject(lists); + oos.close(); + //2. 反序列化list.txt ,并遍历集合,打印对象信息。 + ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt")); + Object o = ois.readObject(); + if (o instanceof ArrayList) { + ArrayList students = (ArrayList) o; + for (Student s : students) { + System.out.println(s); + } + } + } +}