Java 对象序列化与反序列化:存储和读取多个学生信息
import java.io.*; import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ArrayList
// 创建文件输出流对象,将数据写入students.txt文件
FileOutputStream fos = new FileOutputStream("src/students.txt");
// 创建对象输出流对象
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.close();
// 创建文件输入流对象,读取students.txt文件的内容
FileInputStream fis = new FileInputStream("src/students.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
// 从students.txt文件中读取数据
ArrayList<Student> students1 = (ArrayList<Student>) ois.readObject();
for (Student s : students1) {
System.out.println("Student对象的id是 :" + s.getId());
System.out.println("Student对象的name是:" + s.getName());
}
ois.close();
}
}
class Student implements Serializable { private int id; private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
原文地址: https://www.cveoy.top/t/topic/ol61 著作权归作者所有。请勿转载和采集!