Java 对象序列化与反序列化:使用 ObjectOutputStream 和 ObjectInputStream
import java.io.*;
public class Main { public static void main(String[] args) throws IOException, ClassNotFoundException { Student s = new Student(10, 'Lily'); // 创建文件输出流对象,将数据写入student.txt文件 FileOutputStream fos = new FileOutputStream("src/student.txt"); // 创建对象输出流对象 ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(s); oos.close();
// 创建文件输入流对象,读取student.txt文件的内容
FileInputStream fis = new FileInputStream("src/student.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
// 从student.txt文件中读取数据
Student s1 = (Student) ois.readObject();
System.out.println("Student对象的id是 :" + s1.getId());
System.out.println("Student对象的name是:" + s1.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/ol6e 著作权归作者所有。请勿转载和采集!