import com.wt.test.*;
import java.io.*;
import java.util.*;
public class MyDemo {
//序列化
public static void seria() throws IOException {
List<Person> list1 = new ArrayList<>();
List<Student> list2 = new ArrayList<>();
Person p1 = new Person();
Person p2 = new Person();
Student s1 = new Student();
s1.setName("ss");
Student s2 = new Student();
s2.setName("dd");
Student s3 = new Student();
s3.setName("ff");
p1.setName("qq");
list2.add(s1);
list2.add(s2);
list2.add(s3);
p2.setName("ww");
p1.setStudents(list2);
p2.setStudents(list2);
list1.add(p1);
list1.add(p2);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\wt\\Desktop\\temp.data"));
oos.writeObject(list1);
oos.close();
}
//反序列化
public static void deSeria() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\wt\\Desktop\\temp.data"));
List<Person> test = (List<Person>) ois.readObject();
ois.close();
test.forEach(item -> {
System.out.println(item.getName());
item.getStudents().forEach(it -> {
System.out.println(it.getName());
});
System.out.println(">>>>>>>>>>");
});
}
public static void main(String[] args) {
try {
seria();
deSeria();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
package com.wt.test;
import java.io.Serializable;
import java.util.List;
public class Person implements Serializable {
private String name;
private List<Student> students;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
package com.wt.test;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}