[英]How to write non-serialized objects, such as Shapes, in a file so they can then be read later
我有一個類類似於以下基本示例的程序:
public class Vertex extends Circle implements Serializable {
private int vertexID;
private final static double SIZE = 10.0;
// Constructor
public Vertex(int ID, double x, double y) {
super(x, y, SIZE, Color.BLUE);
this.vertexID = ID;
}
}
我想做的是使用ObjectOutputStream
將List<Vertex> myVertices
寫入文件,這要求每個類都實現Serializable
接口。 一個例子如下所示:
FileChooser fc = new FileChooser();
File fileChosen = fc.showOpenDialog(window);
try {
FileOutputStream fOutStream = new FileOutputStream(fileChosen);
ObjectOutputStream oOutStream = new ObjectOutputStream(fOutStream);
oOutStream.writeObject(myVertices);
oOutStream.close();
} catch {
// Exception handling here
}
上述實現的問題在於,盡管Vertex
實現了Serializable
,但超類Circle
及其超類Shape
卻沒有實現Serializable
。 結果是該文件包含Vertex
對象,但是所有Shape
詳細信息都丟失了,默認為0。
有沒有解決此類問題的簡單方法? 我當前唯一的選擇似乎是創建自己的Shape
/ Circle
,將位置/顯示數據存儲為雙精度,以便隨后可以Serializable
。 顯然,對於一堂課來說,這並不需要付出太多的努力,但是我也想保存一些其他Shape
對象。 我認為,然后必須構造實際的Shape
對象才能顯示它們。
謝謝!
您需要創建一個writeObject / readObject方法來保存所需的其他狀態。
序列化中readObject / writeObject的使用
如果有人想查看Shape
的實際代碼,特別是Circle
對象,這是我通過接受的答案實現的。 還包括List<Vertex> myVertices = new ArrayList()
的示例:
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeInt(vertexID);
oos.writeObject(myVertices);
oos.writeDouble(super.getCenterX());
oos.writeDouble(super.getCenterY());
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Read in same order as write
this.vertexID = ois.readInt();
this.myVertices = (List<Vertex>) ois.readObject();
super.setCenterX(ois.readDouble());
super.setCenterY(ois.readDouble());
// Default Circle properties
super.setRadius(SIZE); // Default
super.setFill(Color.BLUE); // Default
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.