2013-04-15 19 views
0

我正在使用JSI(Java Spatial Index,RTree)來實現2D空間搜索。我想將樹保存到文件中,這會使用下面的代碼觸發java.io.NotSerializableExceptionJava在文件中寫入/讀取不可序列化的對象

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; 
     } 
    } 
} 

如何序列化此第三方類,以便我可以讀/寫它? 謝謝。

+0

可能該類沒有實現'Serializable'! – NINCOMPOOP

+0

你能在'output.writeObject(this.spatialIndex);'後面捕獲異常並打印完整的跟蹤嗎?看起來像'try'後面是'finally' – sanbhat

+0

@noob它沒有。這是否意味着我無法將其保存到文件? –

回答

1

由於com.infomatiq.jsi.rtree.RTree未執行Serializable您不能使用Java序列化來持久保存其對象的狀態。您可以使用其他框架進行序列化,如 one here

-1

嘗試擴展它,使擴展類可序列化。那麼你應該可以寫入文件。

+0

僅僅讓一個類擴展一個超類並不能幫助序列化超類。我們需要複製子類中的所有變量,然後序列化。 – sanbhat

1

由於RTree沒有實現Serializable,所以不能使用Java序列化。

+0

謝謝!你能否推薦一些方法來實現寫/讀這樣的對象? –

相關問題