java.io.Serializable 標記介面import java.io.*;
class Student implements Serializable {
private static final long serialVersionUID = 1L; // 版本鎖,防止字段變更導致反序列化失敗
int id;
String name;
transient String sex; // transient 字段不參與序列化
transient int age;
public Student(String name, String sex, int age) {
this.name = name; this.sex = sex; this.age = age;
}
}
public class ObjectIODemo {
private static final String FILE_PATH = "C:\\Users\\bigerf\\Desktop\\objTest.txt";
public static void main(String[] args) throws IOException, ClassNotFoundException {
writeObject();
readObject();
}
// 序列化寫入
public static void writeObject() throws IOException {
File file = new File(FILE_PATH);
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
Student stu = new Student("瑪麗蘇", "男", 18);
oos.writeObject(stu); // 核心方法
}
}
// 反序列化讀取
public static void readObject() throws IOException, ClassNotFoundException {
File file = new File(FILE_PATH);
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
Student stu = (Student) ois.readObject(); // 需強制轉型
System.out.println("name: " + stu.name);
System.out.println("sex: " + stu.sex); // null
System.out.println("age: " + stu.age); // 0
}
}
}
name: 瑪麗蘇
sex: null
age: 0
transient 修飾的 sex、age 未被序列化,反序列化時得到預設值(引用類型 null、基本類型 0)。
InvalidClassException,建議顯式聲明| 方法 | 說明 |
|---|---|
writeObject(Object obj) | 將對象寫入底層流 |
readObject() | 讀取並還原對象,返回 Object 需轉型 |
