Java向/从文件写入/读取不可序列化的对象

时间:2013-04-15 07:28:39

标签: java spatial-index notserializableexception

我使用JSI(Java Spatial Index,RTree)来实现2D空间搜索。我想将树保存到文件,使用下面的代码触发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;
        }
    }
}

如何序列化此第三方课程以便我可以读/写它? 感谢。

3 个答案:

答案 0 :(得分:1)

由于RTree没有实现Serializable,因此无法使用Java Serialization。

答案 1 :(得分:1)

由于com.infomatiq.jsi.rtree.RTree未实现Serializable,因此无法使用Java序列化来保持其对象的状态。您可以使用其他框架进行序列化,例如 one here

答案 2 :(得分:-1)

尝试扩展它,使扩展类可序列化。然后你应该能够写入文件。