// 1.定义多个对象,存储在集合中
ArrayList
list.add(new Student("小孙",30));
list.add(new Student("小王",20));
list.add(new Student("小赵",40));
list.add(new Student("小刘",10));
list.add(new Student("小丽",25));
// 2. 使用序列化技术,把该集合对象写入到文件中
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day30_IO\students.txt"));
// 3. 写入进去,调用writeObject
oos.writeObject(list);
// 4. 使用反序列化技术,把文件中保存的集合对象读取出来
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day30_IO\students.txt"));
// 5. 读取对象数据,调用readObject()方法
Object obj = ois.readObject();
// 6.向下转型
if (obj instanceof ArrayList){
ArrayList
// 7. 遍历该集合对象
for (Object student : students) {
System.out.println(student);
}
}
// 8. 释放资源
ois.close();
oos.close();
}
原文:https://www.cnblogs.com/zlh109/p/14158060.html