'How to access a specific object in serialized data?

I'm using FlatBuffers to serialize a graph for an Android app I'm building (so I don't have to re-build it each time the user opens the app), but I'm having a bit of an issue with the deserialization process.

The graph is represented by a List<Vertex> and here is the important snippet of the Vertex class:

public final class Vertex {
    private final List<Edge> edges = new ArrayList<>();
    private int lbl;
    private float lat;
    private float lon;
    private int actualCostFromSource;
    private int numInitialized;
    private int pqKey;
    private int predecessorLabel = -1;
}

The Edge class is also quite simple:

public final class Edge {
    private final int endVertexLabel;
    private short length;
    private short travelTime;
}

Now, I can serialize and deserialize the complete graph with almost no issues (well, I do have one, but that's for another question). However, when I chose to go with FlatBuffers in the first place, I was under the assumption that I would be able to retrieve a vertex from the serialized data without having to deserialize it completely.

For each vertex I serialized, I saved its offset (the int the corresponding create... method returns) in the serialized data in a text file, so I know that e.g., the zero-th vertex starts at position 68 and, while the first at 144. Can’t I do something like the following the get the former?

ByteBuffer buffer = ByteBuffer.allocateDirect(144 - 68);
// Create an InputStream using the serialized BIN file.
inputStream.getChannel().read(buffer, 68);
Vertex v = Vertex.getRootAsVertex(buffer);

From what I gather from the documentation, this is valid, but the ByteBuffer always throws an IndexOutOfBoundException like this:

Exception in thread "main" java.lang.IndexOutOfBoundsException
    at java.base/java.nio.Buffer.checkIndex(Buffer.java:749)
    at java.base/java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:692)
    at com.dimitrismantas.torch.util.serial.Vertex.getRootAsVertex(Vertex.java:42)
    at com.dimitrismantas.torch.util.serial.Vertex.getRootAsVertex(Vertex.java:36)
    at com.dimitrismantas.torch.Main.main(Main.java:86)

Is what I’m attempting to do even possible? And if so, how do I do it?

Thanks.

P.S: I’ve also noticed that, while my graph has X vertices, the file containing their offsets has less than X entries. What’s up with that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source