Java生成一个学生对象Student,对象有学号,年龄,身高。将学生对象存储到文件,然后从文件中读取数据重新生成Student对象。
时间: 2024-02-16 13:02:51 浏览: 66
好的,以下是实现的Java代码:
```java
import java.io.*;
class Student implements Serializable {
private String num;
private int age;
private double height;
public Student(String num, int age, double height) {
this.num = num;
this.age = age;
this.height = height;
}
public String toString() {
return "学号:" + num + ",年龄:" + age + ",身高:" + height;
}
}
public class Main {
public static void main(String[] args) {
// 创建学生对象
Student student = new Student("20210001", 18, 1.75);
// 将学生对象存储到文件
try {
FileOutputStream fileOut = new FileOutputStream("student.dat");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(student);
objOut.close();
fileOut.close();
} catch(IOException e) {
e.printStackTrace();
}
// 从文件中读取数据重新生成Student对象
Student newStudent = null;
try {
FileInputStream fileIn = new FileInputStream("student.dat");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
newStudent = (Student) objIn.readObject();
objIn.close();
fileIn.close();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(newStudent);
}
}
```
首先我们定义了一个`Student`类,有三个属性:学号、年龄、身高,以及一个`toString`方法用于打印学生对象信息。这个类实现了`Serializable`接口,这样`Student`对象就可以被序列化和反序列化。
然后我们创建了一个`student`对象,将其存储到文件中。使用`ObjectOutputStream`类将`student`对象序列化并存储到文件中。
最后我们使用`ObjectInputStream`类从文件中读取数据并重新生成了一个`newStudent`对象。最后打印`newStudent`对象信息。
阅读全文
相关推荐
















