可以手动给类添加一个序列号格式,在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 2022-07-18 14:16  淤泥不染  阅读(19)  评论(0编辑  收藏  举报