[英]Java writing/reading unserializable objects to/from file
I am using JSI (Java Spatial Index, RTree) to implement 2D spatial search. 我正在使用JSI (Java空间索引,RTree)来实现2D空间搜索。 I want to save the tree to file, which triggered
java.io.NotSerializableException
using code below. 我想将树保存到文件,该文件使用下面的代码触发了
java.io.NotSerializableException
。
public class GeographicIndexer {
private static final Logger log = LoggerFactory.getLogger(GeographicIndexer.class);
public SpatialIndex spatialIndex = null;
public void init() {
this.spatialIndex = new RTree();
this.spatialIndex.init(null);
}
public void add(float x1, float y1, float x2, float y2, int id) {
Rectangle rect = new Rectangle(x1, y1, x2, y2);
this.spatialIndex.add(rect, id);
}
public void add(float x, float y, int id) {
this.add(x, y, x, y, id);
}
public void saveIndex(String indexStorePath) {
try {
OutputStream file = new FileOutputStream(indexStorePath);
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
output.writeObject(this.spatialIndex);
} finally {
output.close();
}
} catch(IOException e) {
log.error("Fail to write geographic index");
e.printStackTrace();
}
}
public GeographicIndexer loadIndex(String indexStorePath) {
try {
InputStream file = new FileInputStream(indexStorePath);
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
this.spatialIndex = (SpatialIndex)input.readObject();
} catch (ClassNotFoundException e) {
log.error("Fail to read geographic index");
} finally {
input.close();
}
return this;
} catch(IOException e) {
log.error("Fail to read geographic index");
return this;
}
}
}
How do I serialize this 3rd party class so that I can read/write it? 我如何序列化该第三方类,以便可以对其进行读取/写入? Thanks.
谢谢。
由于RTree没有实现Serializable,因此不能对其使用Java Serialization。
Since com.infomatiq.jsi.rtree.RTree
doesn't implement Serializable
you cannot use Java Serialization to persist the state of its object . 由于
com.infomatiq.jsi.rtree.RTree
没有实现Serializable
,因此不能使用Java Serialization来保持其对象的状态。 You can use other frameworks for Serialization , like the one here . 您可以使用其他框架进行序列化,例如此处的框架。
Try to extend it, Make the extended class serializable. 尝试扩展它,使扩展的类可序列化。 Then you should be able to write to file.
然后,您应该能够写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.