异常_原理和解决方案以及练习_序列化集合

InvalidClassException异常原理和解决方案

 

 

 

 

练习_序列化集合

练习:序列化集合

  当我们想在文件中保存多个对象的时候

  可以把多个对象存储到一个集合中

  对集合进序列化和反序列化

分析:

  1.定义一个存储Person对象的ArrayList集合

  2.往ArrayList集合中存储Person

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

  4.使用ObjectOutputStream中的方法writeObject对集合进行序列化

  5.创建一个反序列化ObjectInputStream对象

  6.使用ObjectInputStream中的方法readObject读取文件中保存的集合

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

  8.遍历ArrayList集合

  9.释放资源

        //定义一个存储Person对象的ArrayList集合
        ArrayList<Person> list = new ArrayList<>();
        //往ArrayList集合中存储Person元素
        list.add(new Person("张三",18));
        list.add(new Person("李四",14));
        list.add(new Person("王五",32));
        list.add(new Person("赵六",52));
        list.add(new Person("田七",29));
        //创建一个序列化流ObjectOutputStream对象
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("list.txt"));
        //使用ObjectOutputStream中的方法writeObject对集合进行序列化
        objectOutputStream.writeObject(list);
        //创建一个反序列化ObjectInputStream对象
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("list.txt"));
        //使用ObjectInputStream中的方法readObject读取文件中保存的集合
        Object o = objectInputStream.readObject();
        //把Object类型的集合转换为ArrayList类型
        ArrayList<Person> list2 = (ArrayList<Person>)o;
        //遍历ArrayList集合
        for (Person person : list2) {
            System.out.println(person);
        }
        objectOutputStream.close();
        objectInputStream.close();
    }

运行结果:

 

posted @ 2022-07-22 10:21  monkey大佬  阅读(26)  评论(0)    收藏  举报