16.定义一个学生类 Student,有属性,Date brith,String name,int height,String degree,定义两个对象,将此对象写到文件中,并在另外一个工程中,将些内容读出.
时间: 2023-04-02 18:04:08 浏览: 203
好的,这是一个关于 Java 编程的问题。可以回答。
首先,我们可以定义一个学生类 Student,包含属性 Date birth、String name、int height、String degree。然后创建两个对象,将这些对象写入文件中,可以使用 Java 的序列化机制实现。在另一个工程中,可以使用反序列化机制将这些内容读出来。
具体实现可以参考以下代码:
```
import java.io.*;
public class Student implements Serializable {
private Date birth;
private String name;
private int height;
private String degree;
public Student(Date birth, String name, int height, String degree) {
this.birth = birth;
this.name = name;
this.height = height;
this.degree = degree;
}
public static void main(String[] args) {
Student s1 = new Student(new Date(), "Tom", 180, "Bachelor");
Student s2 = new Student(new Date(), "Jerry", 170, "Master");
try {
FileOutputStream fos = new FileOutputStream("students.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.writeObject(s2);
oos.close();
fos.close();
System.out.println("Objects have been written to file");
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("students.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s3 = (Student) ois.readObject();
Student s4 = (Student) ois.readObject();
ois.close();
fis.close();
System.out.println("Objects have been read from file");
System.out.println(s3);
System.out.println(s4);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```