【java】多个对象的序列化和反序列化

时间:2023-03-10 04:28:21
【java】多个对象的序列化和反序列化

当我们需要序列化多个对象的时候,可以采用集合把多个对象放到集合中,然后序列化整个集合。

而我们要反序列化的时候,就使用集合接收反序列化后的对象

如:

List<Student> studentList = new ArrayList<>();
studentList.add(stu1);
studentList.add(stu2);
studentList.add(stu3);
studentList.add(stu4); try(
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("MyCode/src/com/xxxx/Test/stus.txt")); //对象字节输出流关联文件
){ oos.writeObject(studentList); //向stus.txt写入对象(当然我的Student类是实现了序列化接口Serializable)

}catch (Exception e){
e.printStackTrace();
} 以上代码就是把多个Student对象方法一个ArrayList集合中,然后序列化整个集合。
反序列化就如下:
try (
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("MyCode/src/com/xxxx/Test/stus.txt"));
                ){
List<Student> studentList = (ArrayList<Student>)ois.readObject(); //注意这里需要强制转换 System.out.print(studentList); //因为我在Student类中重写了toString()方法。所以可以输出集合中所有对象的信息
}catch (Exception e){ }