练习:序列化集合

练习:序列化集合

当我们想在文件中保存多个对象的时候
可以把多个对象存储到一个集合中
对集合进行序列化和反序列化在这里插入图片描述

分析:
  • 1.定义一个存储Person对象的ArrayList
  • 2.往ArrayList集合中存储Person对象
  • 3.创建一个序列化流ObjectOutputStream
  • 4.使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
  • 5.创建一个反序列化ObjectInputStream对象
  • 6.使用ObjectInputStream对象中的方法readObject方法读取文件中保存的集合
  • 7.把Object类型的集合转换为ArrayList类型
  • 8.遍历ArrayList集合
  • 9.释放资源
package com.IOAndProperties.ObjectStream;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
/*
     练习:序列化集合
          当我们想在文件中保存多个对象的时候
          可以把多个对象存储到一个集合中
          对集合进行序列化和反序列化

      分析:
           1.定义一个存储Person对象的ArrayList
           2.往ArrayList集合中存储Person对象
           3.创建一个序列化流ObjectOutputStream
           4.使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
           5.创建一个反序列化ObjectInputStream对象
           6.使用ObjectInputStream对象中的方法readObject方法读取文件中保存的集合
           7.把Object类型的集合转换为ArrayList类型
           8.遍历ArrayList集合
           9.释放资源
 */

public class Demo03Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 1.定义一个存储Person对象的ArrayList
        ArrayList<Person> list = new ArrayList<>();
        // 2.往ArrayList集合中存储Person对象
        list.add(new Person("杨幂",25));
        list.add(new Person("关晓彤",22));
        list.add(new Person("迪丽热巴",24));
        //3.创建一个序列化流ObjectOutputStream
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("基础语法\\对象集合.txt"));
        //4.使用ObjectOutputStream对象中的方法writeObject,对集合进行序列化
        oos.writeObject(list);
        // 5.创建一个反序列化ObjectInputStream对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("基础语法\\对象集合.txt"));
        // 6.使用ObjectInputStream对象中的方法readObject方法读取文件中保存的集合
        Object o=ois.readObject();
         //7.把Object类型的集合转换为ArrayList类型
        ArrayList<Person> list2 = (ArrayList<Person>)o;
        // 8.遍历ArrayList集合
        for (Person person : list2) {
            System.out.println(person);
        }
        //9.释放资源
        oos.close();
        ois.close();

    }
}

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值