要求定义5个学生对象,数据如下:学生1:("李四", 25, "河南省郑州市"),学生2:("韩梅梅", 19, "焦作市武陟县"),学生3:("李磊", 20, "郑州市中原区"),学生4:("张明", 21, "修武县方庄"),学生5:("吴林", 18, "开封市祥符区")。请将这5个学生对象数据写入到“d:\学生信息.txt”文件中,并在程序中反序列化输出5条学生信息 用java
时间: 2023-07-19 21:41:54 浏览: 80
表示并输出一个学生信息JAVA
好的,以下是代码实现:
```java
import java.io.*;
import java.util.ArrayList;
public class Student {
private String name;
private int age;
private String address;
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
public String toString() {
return "姓名:" + name + ",年龄:" + age + ",地址:" + address;
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("李四", 25, "河南省郑州市"));
students.add(new Student("韩梅梅", 19, "焦作市武陟县"));
students.add(new Student("李磊", 20, "郑州市中原区"));
students.add(new Student("张明", 21, "修武县方庄"));
students.add(new Student("吴林", 18, "开封市祥符区"));
// 将学生信息写入文件
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\学生信息.txt"));
oos.writeObject(students);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化读取学生信息
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\学生信息.txt"));
ArrayList<Student> studentsRead = (ArrayList<Student>) ois.readObject();
ois.close();
for (Student s : studentsRead) {
System.out.println(s.toString());
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
运行程序后,在控制台输出的信息为:
```
姓名:李四,年龄:25,地址:河南省郑州市
姓名:韩梅梅,年龄:19,地址:焦作市武陟县
姓名:李磊,年龄:20,地址:郑州市中原区
姓名:张明,年龄:21,地址:修武县方庄
姓名:吴林,年龄:18,地址:开封市祥符区
```
阅读全文