相关定义:
序列化是将内存中的一些对象,以文件的形式保存在磁盘上,实现对象的持久化存储;而反序列化就是将序列化后的文件,读取到内存中,在内存中得到一个对象。
使用到的类:
ObjectOutputStream和ObjectInputStream
注意事项:
需要序列化的对象所属的类,以及这个类中使用到的其他类(以属性体现),都是需要实现serializable接口。
案例代码:
Person p1 = new Person();
p1.name = "xiaoming";
p1.pet = new Dog("xiaohei", 2);
//序列化对象
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file\\file"))){
oos.writeObject(p1);
oos.flush();
}catch(IOException e){
e.printStackTrace();
}
//反序列化对象
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file\\file"))){
Object o = ois.readObject();
System.out.println((Person)o);
}catch(IOException e){
e.printStackTrace();
}