簡體   English   中英

如何在文件中寫入非序列化對象(例如Shapes),以便以后可以讀取它們

[英]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;
    }
}

我想做的是使用ObjectOutputStreamList<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對象才能顯示它們。

謝謝!

如果有人想查看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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM