进阶day10-序列化流的练习
This commit is contained in:
41
javaSE-day10/src/com/inmind/object_stream03/Test13.java
Normal file
41
javaSE-day10/src/com/inmind/object_stream03/Test13.java
Normal file
@@ -0,0 +1,41 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user