package ObjectStream3;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/*
* 练习:序列化集合
* 当我们想在文件中保存多个对象的时候
* 可以把多个对象存储到一个集合中
* 对集合进行序列化和反序列化
* 分析:
* 1.定义一个Person对象的ArrayList集合,并存储对象
* 2.创建序列化流ObjectOutputStream对象
* 3.使用序列化流中的writeObject(),对集合进行序列化
* 4.创建反序列化objectInputStream对象,使用readObject读取集合
* 5.把object类型的集合转换为Arraylist类型
* 6.遍历集合,释放资源
* */
public class ObjectStreamDemo3 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
List<Person> list = new ArrayList<>();
list.add(new Person("张丹",19));
list.add(new Person("李四",33));
list.add(new Person("王五",48));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e:\\\\javaStudy\\person3.txt"));
oos.writeObject(list);
//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:\\\\javaStudy\\person3.txt"));
ArrayList<Person> ar = (ArrayList<Person>)ois.readObject();
Iterator<Person> it = ar.iterator();
if(it.hasNext()) {
System.out.println(it.next());
}
oos.close();
ois.close();
}
}
序列化集合
最新推荐文章于 2024-08-29 19:35:40 发布