编写一个student类用来描述学生对象,创建若干学生,将其写入文件;再从文件读出学生信息,展示在屏幕上。 java
时间: 2023-10-04 21:04:45 浏览: 77
下面是一个示例代码:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getGrade() {
return grade;
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 18, 90));
students.add(new Student("Jerry", 17, 85));
students.add(new Student("Mary", 18, 95));
// 写入文件
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students.dat"))) {
oos.writeObject(students);
System.out.println("写入成功!");
} catch (IOException e) {
System.out.println("写入失败!");
e.printStackTrace();
}
// 从文件读出学生信息
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students.dat"))) {
List<Student> studentsFromFile = (List<Student>) ois.readObject();
System.out.println("读取成功!");
for (Student student : studentsFromFile) {
System.out.println("姓名:" + student.getName() + ",年龄:" + student.getAge() + ",成绩:" + student.getGrade());
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("读取失败!");
e.printStackTrace();
}
}
}
```
在上面的示例代码中,我们定义了一个 `Student` 类,它有三个属性:姓名、年龄和成绩。我们创建了三个学生对象,并将它们写入到文件中。然后,我们从文件中读出学生信息,并在屏幕上展示出来。
我们使用 `ObjectOutputStream` 和 `ObjectInputStream` 来实现对象的读写。在写入对象时,我们需要将对象转换为字节序列,因此我们需要实现 `Serializable` 接口。在读出对象时,我们需要将字节序列转换为对象,因此我们需要进行类型转换。
注意,我们需要捕获可能抛出的 `IOException` 和 `ClassNotFoundException` 异常。同时,在使用 `ObjectOutputStream` 和 `ObjectInputStream` 时,我们需要使用 try-with-resources 语句来确保资源能够被正确关闭。