代码如下:
public class MyWork {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//序列化
File f = new File("testFile/testObject.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
ArrayList<Student> list1 = new ArrayList<>();
Student s1 = new Student("张三",18);
Student s2 = new Student("李四",19);
Student s3 = new Student("王武",20);
list1.add(s1);
list1.add(s2);
list1.add(s3);
oos.writeObject(list1);
oos.close();
//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
ArrayList<Student> list2 = (ArrayList<Student>) ois.readObject();
Iterator<Student> it = list2.iterator();
while (it.hasNext()) {
Student stu = it.next();
System.out.println(stu.getName() + "======" + stu.getAge());
}
ois.close();
}
}