了解序列化流,实现效果:将若干个Student对象添加到List集合中,然后将List存储到txt文件中,再从txt文件读取内容,并且打印List
时间: 2024-04-11 19:33:25 浏览: 27
可以使用序列化流将若干个Student对象添加到List集合中,然后将List存储到txt文件中。接下来,从txt文件中读取内容,并打印List。以下是一个示例代码:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
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 class SerializationDemo {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student("Alice", 20));
studentList.add(new Student("Bob", 21));
studentList.add(new Student("Charlie", 22));
// 序列化并将List写入文件
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("studentList.txt"))) {
outputStream.writeObject(studentList);
} catch (IOException e) {
e.printStackTrace();
}
// 从文件中读取并反序列化List
List<Student> deserializedList;
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("studentList.txt"))) {
deserializedList = (List<Student>) inputStream.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return;
}
// 打印List中的内容
for (Student student : deserializedList) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}
```
这段代码会将三个Student对象添加到List集合中,并将List存储到名为"studentList.txt"的txt文件中。然后,它会读取该文件,并将内容反序列化为List对象。最后,它会打印List中的每个Student对象的姓名和年龄信息。