java 用io流存储和读取学生信息
时间: 2024-02-15 19:03:03 浏览: 81
好的,以下是一个简单的 Java 程序,可以用 IO 流存储和读取学生信息:
```java
import java.io.*;
public class StudentIO {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1 = new Student("John", "Smith", 18, "Computer Science");
Student s2 = new Student("Mary", "Jones", 19, "Mathematics");
// 存储学生信息到文件
FileOutputStream fos = new FileOutputStream("students.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.writeObject(s2);
oos.close();
fos.close();
// 从文件读取学生信息
FileInputStream fis = new FileInputStream("students.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s3 = (Student)ois.readObject();
Student s4 = (Student)ois.readObject();
ois.close();
fis.close();
// 输出读取到的学生信息
System.out.println(s3);
System.out.println(s4);
}
}
class Student implements Serializable {
private String firstName;
private String lastName;
private int age;
private String major;
public Student(String firstName, String lastName, int age, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.major = major;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getMajor() {
return major;
}
public String toString() {
return firstName + " " + lastName + " (" + age + ") - " + major;
}
}
```
这个程序定义了一个 `Student` 类,该类实现了 `Serializable` 接口,以便可以将其对象序列化到文件中。然后,这个程序创建两个 `Student` 对象,将它们写入文件中,再从文件中读取它们,并将它们的信息输出到控制台上。在这个程序中,我们使用了 `ObjectOutputStream` 和 `ObjectInputStream` 类,它们可以帮助我们将对象写入文件或从文件中读取对象。
阅读全文