0

Here is the code i have for reading a flat buffer file. I always get a EOF exception . How do i get rid of that exception...

  File file = new   File("/Users/samarnath/RmsOne/CreateFlatBuffer/src/com/rms/objects/SingleCoverRiskPolicy.fb");
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
    int size;
    byte[] data = new byte[0];

    while ((randomAccessFile.read(data, 0, 0)) != -1)
    {
        try {
            size = randomAccessFile.readInt();
            data = new byte[size];
            randomAccessFile.read(data, 0, size);

            ByteBuffer bb = ByteBuffer.wrap(data);
            SingleCoverRiskPolicy singleCoverRiskPolicy = SingleCoverRiskPolicy.getRootAsSingleCoverRiskPolicy(bb);
            System.out.println(singleCoverRiskPolicy.id());

        } catch (EOFException e) {

            randomAccessFile.close();
            e.printStackTrace();
        }
    }
user3897533
  • 417
  • 1
  • 8
  • 24

1 Answers1

1

I am confused by your code... First off, byte[] data = new byte[0]; doesn't have any use because you overwrite it later. Secondly, you are creating the new RandomAccessFile() outside of the try-catch. Third, you seem to be passing in 0 for the length of bytes to randomAccessFile.read(buffer, offset, length). If you had meaning for any of these, please comment to clarify.

If you look at the Java Test file, they have an example you can reference: https://github.com/google/flatbuffers/blob/master/tests/JavaTest.java#L30

Try something like this:

*Note: I did not compile this code. But it should be similar enough to address your issues.

File file = new File("/Users/samarnath/RmsOne/CreateFlatBuffer/src/com/rms/objects/SingleCoverRiskPolicy.fb");
RandomAccessFile randomAccessFile = null;
byte[] data = null;

try {
    randomAccessFile = new RandomAccessFile(file, "r");
    data = new byte[(int)randomAccessFile.length()];
    randomAccessFile.readFully(data);
    randomAccessFile.close();
} catch(java.lang.IllegalArgumentException e) {
    e.printStackTrace();
} catch(java.io.IOException e) {
    e.printStackTrace();
} catch(java.io.FileNotFoundException e) {
    e.printStackTrace()
} catch(java.lang.SecurityException e) {
    e.printStackTrace()
} // Note: You can clean up these exceptions as needed (depending on your Java version).

// You're done reading it, now convert to a ByteBuffer and begin using.
ByteBuffer bb = ByteBuffer.wrap(data);
SingleCoverRiskPolicy singleCoverRiskPolicy = SingleCoverRiskPolicy.getRootAsSingleCoverRiskPolicy(bb);
System.out.println(singleCoverRiskPolicy.id());
MrHappyAsthma
  • 6,332
  • 9
  • 48
  • 78