进阶day10-序列化流的练习

This commit is contained in:
2026-03-23 17:22:58 +08:00
parent ab3a5598a7
commit c59f70cb24
2 changed files with 50 additions and 1 deletions

View File

@@ -0,0 +1,41 @@
package com.inmind.object_stream03;
import java.io.*;
import java.util.ArrayList;
/*
1. 将存有多个自定义对象的集合序列化操作保存到list.txt文件中。
2. 反序列化list.txt ,并遍历集合,打印对象信息。
*/
public class Test13 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//创建集合保存学生对象
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("张三", 18));
students.add(new Student("李四", 20));
students.add(new Student("王五", 19));
//序列化保存集合
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
oos.writeObject(students);
oos.close();
//创建反序列化流对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt"));
Object o = ois.readObject();
ArrayList objs = null;
if (o instanceof ArrayList) {
objs = (ArrayList) o;
}
//遍历集合,打印对象信息。
for (Object obj : objs) {
if (obj instanceof Student) {
Student s = (Student) obj;
System.out.println(s.name);
System.out.println(s.age);
System.out.println(s);
}
}
}
}