Java 序列化机制为了节省磁盘空间,具有特定的存储规则,当写入文件的为同一对象时,并不会再将对象的内容进行存储,而只是再次存储一份引用,上面增加的 5 字节的存储空间就是新增引用和一些控制信息的空间。反序列化时,恢复引用关系, t1 和 t2 指向唯一的对象,二者相等,输出 true。该存储规则极大的节省了存储空间。
public class TestSerialTwo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("res.obj"));
TestSerial test = new TestSerial();
// 试图两次将对象写入文件
out.writeObject(test);
out.flush();
System.out.println(new File("res.obj").length());
out.writeObject(test);
out.close();
System.out.println(new File("res.obj").length());
ObjectInputStream oin = new ObjectInputStream(new FileInputStream("res.obj"));
// 从文件中依次读出两个对象
TestSerial t1 = (TestSerial) oin.readObject();
TestSerial t2 = (TestSerial) oin.readObject();
oin.close();
// 判断两个引用是否指向同一个对象
System.out.println(t1 == t2);
}
}
静态变量序列化,序列化并不保存静态变量
public class TestStaticSerial implements Serializable {
private static final long serialVersionUID = 1L;
public static int staticVar = 5;
public static void main(String[] args) {
try {
// 初始化时staticVar为5
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("result.obj"));
out.writeObject(new TestStaticSerial());
out.close();
TestStaticSerial.staticVar = 10;
// 序列化后改为10
ObjectInputStream oin = new ObjectInputStream(new FileInputStream("result.obj"));
TestStaticSerial t = (TestStaticSerial) oin.readObject();
oin.close();
// 再读取一次staticVar的新值;
System.out.println(t.staticVar);
} catch (Exception e) {
// TODO: handle exception
}
}
}