序列化集合

package com.itcast.demo06.ObjectStream;

import java.io.*;
import java.util.ArrayList;

/**
* @author newcityman
* @date 2019/7/28 - 23:15
* 练习:序列化集合
* 步骤:
* 1、定义一个存储Person对象的ArrayList集合
* 2、往集合中存储person对象
* 3、创建一个序列化流ObjectOutputStream,对集合进行序列化
* 4、使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
* 5、创建一个反序列化流ObjectInputStream
* 6、使用ObjectInputStream对象中的方法readObject读取文件中保存的集合
* 7、把Object类型的集合转换成ArrayList类型
* 8、遍历ArrayList结合
* 9、释放资源
*/
public class Demo03Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 1、定义一个存储Person对象的ArrayList集合
ArrayList<Person> pList = new ArrayList<>();
// 2、往集合中存储person对象
pList.add(new Person("张山峰",70));
pList.add(new Person("赵义勇",20));
pList.add(new Person("李敏",30));
// 3、创建一个序列化流ObjectOutputStream,对集合进行序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day18_IOAndProperties\person.txt"));
// 4、使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
oos.writeObject(pList);
// 5、创建一个反序列化流ObjectInputStream
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day18_IOAndProperties\person.txt"));
// 6、使用ObjectInputStream对象中的方法readObject读取文件中保存的集合
Object o = ois.readObject();
// 7、把Object类型的集合转换成ArrayList类型
ArrayList<Person> list = (ArrayList<Person>)o;
// 8、遍历ArrayList结合
for (Person person : list) {
System.out.println(person);
}
ois.close();
oos.close();
}
}
原文地址:https://www.cnblogs.com/newcityboy/p/11261547.html