共計 848 個字符,預計需要花費 3 分鐘才能閱讀完成。
要實現 Java 中的對象序列化,需要按照以下步驟進行:
- 在需要進行序列化的類上實現
Serializable
接口。Serializable
接口是一個標記接口,不包含任何方法,只是用來標記該類可以被序列化。
public class MyClass implements Serializable {// 類的內容}
- 創建一個
ObjectOutputStream
對象來將對象序列化為字節流。
MyClass obj = new MyClass();
try {FileOutputStream fileOut = new FileOutputStream("obj.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();} catch (IOException i) {i.printStackTrace();
}
- 創建一個
ObjectInputStream
對象來從字節流中反序列化對象。
MyClass obj = null;
try {FileInputStream fileIn = new FileInputStream("obj.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
obj = (MyClass) in.readObject();
in.close();
fileIn.close();} catch (IOException i) {i.printStackTrace();
} catch (ClassNotFoundException c) {c.printStackTrace();
}
以上就是實現 Java 中序列化的基本步驟。需要注意的是,被序列化的類的成員變量也必須是可序列化的,否則會拋出 NotSerializableException
異常。如果某個成員變量不希望被序列化,可以使用 transient
關鍵字標記。
丸趣 TV 網 – 提供最優質的資源集合!
正文完