目录
- 什么是序列化和反序列化
- 为什么要序列化
- 如何使用
1.序列化和反序列化
- 把对象转换为字节序列的过程称为对象的序列化。
serialize Object → File : create an ObjectOutputStream with a FileOutputStream.
OutputStream os=new FileOutputStream(“a.txt”);
serialize Object → sequences of bytes →File
1) 创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出流;
2) 通过对象输出流的writeObject()方法写对象。 - 把字节序列恢复为对象的过程称为对象的反序列化。
deserialize File→ Object :create an ObjectInputStream with a FileInputStream.
InputStream os=new FileInputStream(“a.txt”);
File → sequences of bytes →serialize Object
1) 创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流;
2) 通过对象输入流的readObject()方法读取对象

2.为什么要序列化
- 在JVM级别,对象是在堆中创建的;在计算机结构中,它是在内存中创建的,在程序运行完,对象消失。序列化可以长久的保存此对象的数据。
- 需要存储在磁盘上或通过网络传输的数据结构,序列化是一个很好的解决方案。磁盘或网络知道如何存储或传输数据,但它们不了解特定语言存储数据的方式。序列化为语言或编程环境提供了将其数据结构转换为标准格式的标准过程。
3.如何使用
@Test
public void test2(){
File file = new File("D:/test.txt");
Role role = new Role(1L, "role", "note");
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(role);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
Role role1 = (Role) in.readObject();
System.out.println(role1);
System.out.println(role1.equals(role));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public class Role implements Serializable {
private static final long serialVersionUID = 4603642343377807741L;
private Long id;
private String roleName;
private String note;
}
参考:
https://blog.youkuaiyun.com/jiangshangchunjiezi/article/details/105515489?depth_1-utm_source=distribute.pc_feed.185512&utm_source=distribute.pc_feed.185512