Student类代码如下:
java Copy code
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L; // 序列化版本号
private String name;
private String id;
private int age;
public Student(String name, String id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "Name: " + name + ", ID: " + id + ", Age: " + age;
}
}
创建若干学生并将其写入文件的代码如下:
java Copy code
import java.io.*;
import java.util.*;
public class WriteStudentsToFile {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", "123", 20));
students.add(new Student("Jerry", "456", 21));
students.add(new Student("Mary", "789", 22));
try {
File file = new File("students.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
for (Student s : students) {
oos.writeObject(s);
}
oos.close();
System.out.println("Successfully wrote students to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
从文件读出学生信息并展示在屏幕上的代码如下:
java Copy code
import java.io.*;
public class ReadStudentsFromFile {
public static void main(String[] args) {
try {
File file = new File("students.txt");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
try {
while (true) {
Student s = (Student) ois.readObject();
System.out.println(s);
}
} catch (EOFException e) {
// 读到文件末尾,停止读取
System.out.println("Successfully read students from file.");
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在main方法中模拟输入输出:
java Copy code
public static void main(String[] args) {
// 写入学生信息到文件
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", "123", 20));
students.add(new Student("Jerry", "456", 21));
students.add(new Student("Mary", "789", 22));
try {
File file = new File("students.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
for (Student s : students) {
oos.writeObject(s);
}
oos.close();
System.out.println("Successfully wrote students to file.");
} catch (IOException e) {
e.printStackTrace();
}
// 从文件中读取并输出学生信息
try {
File file = new File("students.txt");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
try {
while (true) {
Student s = (Student) ois.readObject();
System.out.println(s);
}
} catch (EOFException e) {
// 读到文件末尾,停止读取
System.out.println("Successfully read students from file.");
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
模拟输出结果如下:
code Copy code
Name: Tom, ID: 123, Age: 20
Name: Jerry, ID: 456, Age: 21
Name: Mary, ID: 789, Age: 22
Successfully wrote students to file.
Name: Tom, ID: 123, Age: 20
Name: Jerry, ID: 456, Age: 21
Name: Mary, ID: 789, Age: 22
Successfully read students from file.