题目:学生数据存储。 编写一个student类用来描述学生对象,创建若干学生,将其写入文件;再从文件读出学生信息,展示在屏幕上。java
时间: 2024-03-30 19:34:17 浏览: 80
下面是一个简单的示例代码,实现了学生信息的存储和读取:
```java
import java.io.*;
public class Student implements Serializable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
// 创建学生对象
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 20);
Student s3 = new Student("王五", 22);
// 将学生信息写入文件
try {
FileOutputStream fos = new FileOutputStream("students.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 从文件读出学生信息并展示
try {
FileInputStream fis = new FileInputStream("students.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("学生信息如下:");
System.out.println("=================");
while (true) {
Student s = (Student) ois.readObject();
System.out.println("姓名:" + s.getName());
System.out.println("年龄:" + s.getAge());
System.out.println("-----------------");
}
} catch (EOFException e) {
System.out.println("文件读取完毕!");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们定义了一个 `Student` 类,实现了 `Serializable` 接口,以便将其对象序列化写入文件。在 `main` 方法中,我们创建了三个学生对象,并将它们写入文件 `students.txt` 中。接着,我们打开文件并读出学生信息,展示在屏幕上。
需要注意的是,在读取文件时,我们使用了 `ObjectInputStream` 类,它可以将文件中的字节流反序列化为对象。在读取文件时,我们使用了一个 `while` 循环,不断读出学生对象,直到文件读取完毕。由于文件中的对象类型都是 `Student`,因此我们可以将读出的对象强制转换为 `Student` 类型。在读取文件时,需要注意捕获 `EOFException` 异常,以便在读取完毕后退出循环。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)