|
@@ -0,0 +1,63 @@
|
|
|
+package com.sf.javase.io.serial;
|
|
|
+
|
|
|
+import lombok.AllArgsConstructor;
|
|
|
+import lombok.Data;
|
|
|
+import lombok.SneakyThrows;
|
|
|
+
|
|
|
+import java.io.*;
|
|
|
+
|
|
|
+// Serializable 可序列化的
|
|
|
+@Data
|
|
|
+@AllArgsConstructor
|
|
|
+public class Person implements Serializable {
|
|
|
+
|
|
|
+ // 生成一个序列化的版本id (序列化编号)
|
|
|
+ // 如果手写,一般写作 1L
|
|
|
+ // 如果生成,会根据当前类的结构,来计算出一个id
|
|
|
+ // 注意点击生成时 鼠标要在类里才有对应显示
|
|
|
+// private static final long serialVersionUID = 1L;
|
|
|
+// private static final long serialVersionUID = -8452582517235146125L;
|
|
|
+ // 重新生成id
|
|
|
+ private static final long serialVersionUID = 3409425097949035146L;
|
|
|
+
|
|
|
+ private String name;
|
|
|
+ private long age;
|
|
|
+ // 如果要被序列化的类 还有别的属性是自定义的类型 那么这个类型也需要是可序列化的
|
|
|
+ private Health health;
|
|
|
+
|
|
|
+ @SneakyThrows
|
|
|
+ public static void main(String[] args) {
|
|
|
+// Health health = new Health("良好");
|
|
|
+// Person person = new Person("zhangsan", 80, health);
|
|
|
+// Person person2 = new Person("lisi", 60, health);
|
|
|
+ // bin 是 binary(二进制文件)
|
|
|
+// FileOutputStream fos = new FileOutputStream("data/person.bin");
|
|
|
+// ObjectOutputStream oos = new ObjectOutputStream(fos);
|
|
|
+// // 将对象写入到文件中
|
|
|
+ // 可以一起序列化多个对象
|
|
|
+// oos.writeObject(health);
|
|
|
+// oos.writeObject(person);
|
|
|
+// oos.writeObject(person2);
|
|
|
+
|
|
|
+ // 当使用一个类的版本进行序列化后 Person(int age)
|
|
|
+ // 改变了类的版本Person(long age) 再对原来的文件进行反序列化
|
|
|
+
|
|
|
+ // 反序列化
|
|
|
+ ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/person.bin"));
|
|
|
+ // 当文件中有多个对象时,写入的顺序就是读出的顺序
|
|
|
+ Health health1 = (Health) ois.readObject();
|
|
|
+ Person result1 = (Person) ois.readObject();
|
|
|
+ Person result2 = (Person) ois.readObject();
|
|
|
+ System.out.println(health1);
|
|
|
+ System.out.println(result1);
|
|
|
+ System.out.println(result2);
|
|
|
+
|
|
|
+ // true true
|
|
|
+ // 同一个对象 只会被序列化一次
|
|
|
+// System.out.println(health1 == result1.getHealth());
|
|
|
+// System.out.println(health1 == result2.getHealth());
|
|
|
+
|
|
|
+ // java中有几种创建对象的方式
|
|
|
+ // new 、反序列化、 反射
|
|
|
+ }
|
|
|
+}
|