了解序列化流,实现效果:将若干个Student对象添加到List集合中,然后将List存储到txt文件中,再从txt文件读取内容,并且打印List
时间: 2024-04-11 18:33:27 浏览: 111
了解序列化流,可以通过使用Java的ObjectOutputStream和ObjectInputStream类来实现将对象序列化到文件和从文件中反序列化对象的操作。下面是实现将Student对象添加到List集合中,然后将List存储到txt文件中,再从txt文件读取内容并打印List的示例代码:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class SerializationExample {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
// 添加Student对象到List集合中
studentList.add(new Student("Alice", 20));
studentList.add(new Student("Bob", 21));
studentList.add(new Student("Charlie", 22));
// 将List存储到txt文件中
serializeList(studentList, "students.txt");
// 从txt文件读取内容并打印List
List<Student> deserializedList = deserializeList("students.txt");
printList(deserializedList);
}
private static void serializeList(List<Student> list, String fileName) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
oos.writeObject(list);
System.out.println("List已序列化到文件" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<Student> deserializeList(String fileName) {
List<Student> list = new ArrayList<>();
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
list = (List<Student>) ois.readObject();
System.out.println("从文件" + fileName + "中反序列化List成功");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return list;
}
private static void printList(List<Student> list) {
for (Student student : list) {
System.out.println(student);
}
}
}
class Student implements Serializable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
运行以上代码,会将List中的Student对象序列化到名为"students.txt"的txt文件中,并从该文件中反序列化List内容并打印出来。
阅读全文