Files
javaSE-0113/javaSE-day10/src/com/inmind/object_stream03/Test13.java

42 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}
}
}
}