[英]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.