1 . 何为序列化
序列化:将对象转化为字节序列的过程( ObjectOutputStream)
2 . 何为反序列化
反序列化:将字节序列转化为对象的过程( ObjectInputStream)
3.为什么要序列化
(1)需要将数据在网络上传输、需要将数据共享的对象 进行持久化
(2)对象需要持久化在本地磁盘中,将长时间不活动的对象持久化到磁盘,当在服务器中找不到时再到本地磁盘查找,避免占用服务器内存
4.如何实例化?
(1)在需要实例化的对象 实现Serializable接口
(2)生成serialVersionUID
(3)测试
A.测试序列化
在本地建一个空的文件a.txt ,使用ObjectOutputStream序列化输出对象将对象序列化
public class TestProduct {
public static void main(String[] args) {
try {
OutputStream op = new FileOutputStream("E:/product"+File.separator+"a.txt");
ObjectOutputStream ops = new ObjectOutputStream(op);
ops.writeObject(new Product("2", "C", "adeline", "Cat" ));
ops.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
序列化测试结果:
B.测试反序列化
InputStream in = new FileInputStream("E:/product"+File.separator+"a.txt");
ObjectInputStream os = new ObjectInputStream(in);
byte[] buffer = new byte[10];
int len = -1;
Product p = (Product) os.readObject();
System.out.println(p);
os.close();
测试结果: