posts - 397,comments - 0,views - 25332

可以手动给类添加一个序列号格式,在SerialiVersionUID接口中规定:

可序列化类可以通过声明名为”serialVersionUID”的字段(该字段必须是静态(static)、最终(final)的long型字段)显示声明其自己的serialVersionUID:

Static final long serialVersionUID=421;(常量不能变)

当JVM反序列化对象时,能找到class文件,但是class文件序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个InvalidClassException异常

 

原理图:

代码实现:

 

 

 

复制代码
public static void main(String[] args) throws IOException {

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("person.txt"));
        objectOutputStream.writeObject(new Person("小美女",18));
        objectOutputStream.close();
    }


    //反序列化
    public static void main(String[] args) throws IOException, ClassNotFoundException {


        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("person.txt"));
        Object o = objectInputStream.readObject();
        objectInputStream.close();

        System.out.println(o);
        Person p = (Person)o;
        System.out.println(p.getName()+p.getAge());
复制代码

 

 

 

 

案例_序列化集合

练习:序列化集合
  当我们想在文件中保存多个对象的时候可以把多个对象存储到一个集合中
  对集合进序列化和反序列化
分析:
  1-定义一个存储Person对象的ArrayList集合

  2.往ArrayList集合中存储Person对象

  3.创建一个序列化流objectoutputStream对象

  4.使用objectoutputstream对象中的方法writeobject,对集合进行序列化

  5.创建—个反序列化objectInputStream对象

  6.使用objectInputstream对象中的方法readobject读取文件中保存的集合

  7.把object类型的集合转换为ArrayList类型

  8.遍历ArrayList集合
  9.释放资源

 

代码:

 

 

posted on   淤泥不染  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示