解决方案
将所有的对象放到一个集合里,随后将集合通过序列化流写到本地
再反序列化这个集合,打印出集合里面所有的对象
public class 写多个对象 {
public static void main(String[] args) throws IOException {
/*
需求:将多个自定义对象序列化到文件中,但是不确定对象个数应该怎么办呢?
将对象放到集合里,序列化这个集合,再反序列化这个集合
*/
Student student1=new Student(23,"zhangsan");
Student student2=new Student(24,"lisi");
Student student3=new Student(25,"wangwu");
Student student4=new Student(26,"zhaoliu");
ArrayList<Student> list=new ArrayList<>();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("/Users/XXX/IdeaProjects/basecode/day02/aaaa/a.txt"));
oos.writeObject(list);
oos.close();
}
}
public class 读多个对象 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建对象
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("/Users/XXX/IdeaProjects/basecode/day02/aaaa/a.txt"));
//读取数据
ArrayList<Student> list=(ArrayList<Student>) ois.readObject();
for (Student stu:list){
System.out.println(stu);
}
ois.close();
}
}