簡體   English   中英

Java向文件/從文件讀取不可序列化的對象

[英]Java writing/reading unserializable objects to/from file

我正在使用JSI (Java空間索引,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;
        }
    }
}

我如何序列化該第三方類,以便可以對其進行讀取/寫入? 謝謝。

由於RTree沒有實現Serializable,因此不能對其使用Java Serialization。

由於com.infomatiq.jsi.rtree.RTree沒有實現Serializable ,因此不能使用Java Serialization來保持其對象的狀態。 您可以使用其他框架進行序列化,例如此處的框架。

嘗試擴展它,使擴展的類可序列化。 然后,您應該能夠寫入文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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