了解序列化流,实现效果:将若干个Student对象添加到List集合中,然后将List存储到txt文件中,再从txt文件读取内容,并且打印List。(自动序列化流)

import java.io.*;
import java.util.ArrayList;
import java.util.List;

class Student implements Serializable {
    private String id;
    private String name;
    private int age;
    private String className;

    public Student(String id, String name, int age, String className) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.className = className;
    }

    // Getters and setters

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", className='" + className + '\'' +
                '}';
    }
}

public class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("1", "Alice", 18, "Class A"));
        studentList.add(new Student("2", "Bob", 20, "Class B"));
        studentList.add(new Student("3", "Charlie", 22, "Class C"));

        String fileName = "students.txt";

        // 将 List 存储到文件
        try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName))) {
            outputStream.writeObject(studentList);
            System.out.println("List 存储到文件成功");
        } catch (IOException e) {
            System.out.println("List 存储到文件失败: " + e.getMessage());
        }

        // 从文件读取内容并打印 List
        try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(fileName))) {
            List<Student> readList = (List<Student>) inputStream.readObject();
            System.out.println("\n从文件读取的 List:");
            for (Student student : readList) {
                System.out.println(student);
            }
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("从文件读取内容失败: " + e.getMessage());
        }
    }
}

在上述示例代码中,我们定义了一个 Student 学生类,并实现了 Serializable 接口,以便将对象序列化和反序列化。

首先,我们创建一个 studentList 列表,并将若干个 Student 对象添加到该列表中。

然后,我们指定一个文件名(students.txt)来存储列表。

使用 ObjectOutputStream 类和 FileOutputStream 类将 studentList 对象写入到文件中。然后,我们使用 ObjectInputStream 类和 FileInputStream 类从文件中读取内容,并将读取的内容转换为 List<Student> 类型。

最后,我们遍历读取的列表并打印每个学生对象。

请确保运行代码时,文件名指定的路径下有读写权限。运行示例代码后,将会将 studentList 写入到文件中,并从文件中读取内容并打印列表中的学生对象。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值