package com.chunzhi.Test04ObjectStream;
import java.io.*;
import java.util.ArrayList;
/*
练习:序列化集合
当我们想在文件中保存多个对象的时候
可以把多个对象储存到一个集合中
对集合进行序列化和反序列化
*/
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 1.定义了一储存Person对象的ArrayList集合
ArrayList<Person> list = new ArrayList<>();
// 2.往ArrayList集合中储存Person对象
list.add(new Person("迪丽热巴", 22));
list.add(new Person("古力娜扎", 19));
list.add(new Person("玛尔扎哈", 26));
// 3.创建一个序列化ObjectOutputStream对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Day10_IO\\序列化练习.txt"));
// 4.使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
oos.writeObject(list);
// 5.创建一个反序列化ObjectInputStream对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Day10_IO\\序列化练习.txt"));
// 6.使用ObjectInputStream对象中的方法readObject读取文件中保存的集合
Object person = ois.readObject();
// 7.把Object类型的集合转换为ArrayList类型
ArrayList<Person> list1 = (ArrayList<Person>) person;
// 8.遍历ArrayLis集合
for (Person person1 : list1) {
System.out.println(person1);
}
// 9.释放资源
ois.close();
oos.close();
}
}