0

I am using JSI (Java Spatial Index, RTree) to implement 2D spatial search. I want to save the tree to file, which triggered java.io.NotSerializableException using code below.

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.

Nathaniel Ding
  • 166
  • 1
  • 10

3 Answers3

1

Since RTree does not implement Serializable you cannot use Java Serialization for it.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Since com.infomatiq.jsi.rtree.RTree doesn't implement Serializable you cannot use Java Serialization to persist the state of its object . You can use other frameworks for Serialization , like the one here .

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
-1

Try to extend it, Make the extended class serializable. Then you should be able to write to file.

Sajith Silva
  • 823
  • 1
  • 13
  • 24
  • Merely making a class extend a Superclass doesnt help serialize the super-class. We need to copy all the variables in the child class and then serialize. – sanbhat Apr 15 '13 at 07:39