为了账号安全,请及时绑定邮箱和手机立即绑定

谈谈 java 中的序列化

标签:
Java

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
     }
  }
}
点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消