s-day10-序列化流的练习
This commit is contained in:
@@ -0,0 +1,38 @@
|
|||||||
|
package com.inmind.object_stream03;
|
||||||
|
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
/*
|
||||||
|
序列化流的练习
|
||||||
|
|
||||||
|
需求:
|
||||||
|
1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。
|
||||||
|
2. 反序列化list.txt ,并遍历集合,打印对象信息。
|
||||||
|
*/
|
||||||
|
public class Test11 {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
//1. 将存有多个自定义对象的集合序列化操作,保存到list.txt文件中。
|
||||||
|
ArrayList<Student> lists = new ArrayList<>();
|
||||||
|
lists.add(new Student("张三1", 18));
|
||||||
|
lists.add(new Student("张三2", 19));
|
||||||
|
lists.add(new Student("张三3", 20));
|
||||||
|
lists.add(new Student("张三4", 21));
|
||||||
|
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
|
||||||
|
oos.writeObject(lists);
|
||||||
|
oos.close();
|
||||||
|
//2. 反序列化list.txt ,并遍历集合,打印对象信息。
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt"));
|
||||||
|
Object o = ois.readObject();
|
||||||
|
if (o instanceof ArrayList) {
|
||||||
|
ArrayList<Student> students = (ArrayList<Student>) o;
|
||||||
|
for (Student s : students) {
|
||||||
|
System.out.println(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user