package com.anyan.day17;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/**
* @author anyan
* @date 2021/5/2-20:15
*/
/*
序列化(serialize):将内存中的对象以数据包的形式放到硬盘文件中,永久保存。拆分对象的过程
ObjectOutputStream类 负责序列化
反序列化(deserialize):将硬盘中数据重新恢复到内存当中。组装对象的过程。
ObjectInputStream类 负责反序列化
参与序列化与反序列化的对象必须实现Serializable接口,该接口是一个标志性接口,其中没有任何方法/属性
Serializable 标志性接口,不包含任何的属性和方法,其作用是其标识作用,提供给Java虚拟机参考,
Java虚拟机识别到该标识后,会自动为实现该接口的类生成一个版本序列号
*/
public class ObjectOutputStreamTest {
public static void main(String[] args) throws Exception {
Student s=new Student("zhangsan",20);
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("Students"));//包装流与节点流
oos.writeObject(s);
oos.flush();
oos.close();
System.out.println(s);
}
}
///反序列化
package com.anyan.day17;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
/**
* @author anyan
* @date 2021/5/2-20:42
*/
/*
反序列化:将硬盘上的数据恢复到内存中并按原来的形式组装起来,使用大的IO流类型为:ObjectInputStream类
*/
public class ObjectInputStreamTest {
public static void main(String[] args) throws Exception{
// Student s=new Student("zhansan ",20);
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Students"));//包装流与节点流(相对而言)
Object obj = ois.readObject();
System.out.println(obj);
ois.close();
}
}