已定义Student类,如下所示: public class Student implements Serializable{ private static final long serialVersionUID = 1L; //序列化串行标识 private String name; private int age; private String address; public Student(String name, int age, String address) { super(); this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", address=" + address + "]"; } } 要求定义5个学生对象,数据如下:学生1:("李四", 25, "河南省郑州市"),学生2:("韩梅梅", 19, "焦作市武陟县"),学生3:("李磊", 20, "郑州市中原区"),学生4:("张明", 21, "修武县方庄"),学生5:("吴林", 18, "开封市祥符区")。 请将这5个学生对象数据写入到“d:\\学生信息.txt”文件中,并在程序中反序列化输出5条学生信息。
时间: 2024-03-21 15:43:50 浏览: 61
Android中Serializable和Parcelable序列化对象详解
代码如下:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
// 创建5个学生对象
Student s1 = new Student("李四", 25, "河南省郑州市");
Student s2 = new Student("韩梅梅", 19, "焦作市武陟县");
Student s3 = new Student("李磊", 20, "郑州市中原区");
Student s4 = new Student("张明", 21, "修武县方庄");
Student s5 = new Student("吴林", 18, "开封市祥符区");
// 将学生对象添加到列表中
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
try {
// 将学生对象列表写入文件
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\学生信息.txt"));
oos.writeObject(students);
oos.close();
// 读取文件中的学生对象列表并输出信息
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\学生信息.txt"));
List<Student> studentsRead = (List<Student>) ois.readObject();
for (Student student : studentsRead) {
System.out.println(student);
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
输出结果如下:
```
Student [name=李四, age=25, address=河南省郑州市]
Student [name=韩梅梅, age=19, address=焦作市武陟县]
Student [name=李磊, age=20, address=郑州市中原区]
Student [name=张明, age=21, address=修武县方庄]
Student [name=吴林, age=18, address=开封市祥符区]
```
阅读全文