Java中序列化流的基本使用

本文详细介绍了如何使用Java的ObjectOutputStream和ObjectInputStream进行对象的序列化和反序列化,包括将对象写入文件及从文件中读取对象的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

序列化流

  • 高级流
  • 需要依托低级流
  • ObjectOutputStream
  • ObjectInputStream
ObjectOutputStream
  • 将java对象写入文件

  • 基本用法

    @Test
    public void objectOutputStreamTest(){
        try {
            FileOutputStream outputStream = new FileOutputStream("E:/ObjectOutputStreamTest.txt");
            //使用低级流初始化ObjectOutputStream
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            //将对象写入文件中(注:该类必须实现Serializable接口)
            oos.writeObject(new Student("赵玉龙", 3));
            //释放资源 
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
ObjectInputStream
  • 从从文件中读取java对象

  • 基本用法

    @Test
    public void objectInputStreamTest(){
        try {
            FileInputStream inputStream = new FileInputStream("E:/ObjectOutputStreamTest.txt");
            //使用低级流初始化ObjectInputStream
            ObjectInputStream ois = new ObjectInputStream(inputStream);
            Student student = (Student) ois.readObject();
            ois.close();
            System.out.println(student);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    
案例:将java对象写入文件后读取它
@Test
public void writeObjects(){
    //实例化一组java对象
    List<Student> students = new ArrayList<>();
    students.add(new Student("张三", 3));
    students.add(new Student("李四", 3));
    students.add(new Student("王五", 3));
    try {
        //实例化一个ObjectOutputStream对象用来写
        FileOutputStream outputStream = new FileOutputStream("E:/writeObjects.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        //将一组java对象放到List中后写入文件
        objectOutputStream.writeObject(students);
        objectOutputStream.close();
        //实例化一个ObjectInputStream对象用来读
        FileInputStream inputStream = new FileInputStream("E:/writeObjects.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        //从文件中将之前写入的List读取到一个新的List对象中
        List<Student> studentList = new ArrayList<>();
        studentList = (List<Student>) objectInputStream.readObject();
        
        System.out.println(studentList);
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值