Student类
import java.io.Serializable;
import java.util.List;
public class Student implements Serializable {
private String stuNum;
private String stuName;
private List<String> teacherList;
public Student(){
}
public Student(String stuNum, String stuName, List<String> teacherList) {
this.stuNum = stuNum;
this.stuName = stuName;
this.teacherList = teacherList;
}
@Override
public String toString() {
return "Student{" +
"stuNum='" + stuNum + '\'' +
", stuName='" + stuName + '\'' +
", teacherList=" + teacherList +
'}';
}
public String getStuNum() {
return stuNum;
}
public void setStuNum(String stuNum) {
this.stuNum = stuNum;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public List<String> getTeacherList() {
return teacherList;
}
public void setTeacherList(List<String> teacherList) {
this.teacherList = teacherList;
}
}
MySerialize类
import java.io.*;
public class MySerialize {
/**
*将对象序列化到指定文件中
* @param obj
* @param fileName
* @throws IOException
*/
public static void mySerialize(Object obj,String fileName) throws IOException {
OutputStream out = new FileOutputStream(fileName);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(obj);
objOut.close();
}
/**
* 从指定文件中反序列化对象
* @param fileName
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static Object myDeserialize(String fileName) throws IOException,ClassNotFoundException{
InputStream in = new FileInputStream(fileName);
ObjectInputStream objIn = new ObjectInputStream(in);
Object obj = objIn.readObject();
return obj;
}
}
Main 类
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> teacherList = new ArrayList<>();
teacherList.add("张三");
teacherList.add("李四");
Student stu1 = new Student("1001","王二",teacherList);
System.out.println("原始对象"+stu1);
String fileName = "stu01.txt";
try {
//对象的序列化
MySerialize.mySerialize(stu1,fileName);
System.out.println("序列化对象完毕!okk!!!");
//对象的反序列化
Object obj = MySerialize.myDeserialize(fileName);
if(obj instanceof Student){
Student stuNew = (Student) obj;
System.out.println("反序列化之后的对象"+stuNew);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果: