本文主要关注的是二进制序列化后的二进制内容解读。通过解读这些看似枯燥的内容,可以让我们做到心中有底——为什么一端序列化出来的二进制流能在另外一端完整地复原?

1. 样例代码

代码如下, 省略不关心的部分

  1. public class Employee implements Serializable {
  2. private String name;
  3. private double salary;
  4. private Date hireDay;
  5. public Employee(String n, double s, int year, int month, int day) {
  6. name = n;
  7. salary = s;
  8. GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
  9. hireDay = calendar.getTime();
  10. }
  11. // 略
  12. }
  13. public class Tester{
  14. private static final String SAVED_PATH = "src/main/java/objectStream/employee.dat";
  15. public static void main(String[] args) throws IOException, ClassNotFoundException {
  16. // 持久化到本地存储中
  17. Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
  18. try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(SAVED_PATH))) {
  19. out.writeObject(obj);
  20. }
  21. }

2. 解读

以下是在notepad++下以hex模式打开的文件截图
Java序列化 - 二进制格式详解 - 图1
https://blog.csdn.net/lqzkcx3/article/details/79463450