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
写入到文件中,并从文件中读取内容并打印列表中的学生对象。