序列化:即将对象信息通过编码后存入文件
反序列化:将文件中序列化的对象信息反序列化读出
需要注意的是需要序列化的对象的实体类必须实现Serializable接口
以下方法代码表示将Student集合整体序列化后存入本地文件(D:/student.data)
/**
* 将传入的学生集合序列化
* @param stu
*/
public void writeStudentData(List<Student> stuList){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("D:/student.data")));
oos.writeObject(stuList);
oos.close();
System.out.println("对象集合序列化成功");
} catch (Exception e) {
e.printStackTrace();
}
}
以下为反序列化代码,将序列化的对象集合取出来并返回,文件路径为:D:/student.data
/**
* 从文件中读取所有序列化了的对象
* 并返回一个集合
* @param stu
* @return
*/
public List<Student> readStudentData(){
List<Student> stuList = new ArrayList<>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("D:/student.data")));
stuList = (List<Student>)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return stuList;
}
以上代码仅供参考