0

这是我用于读取平面缓冲区文件的代码。我总是得到一个 EOF 异常。我如何摆脱那个异常......

  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();
        }
    }
4

1 回答 1

1

我对您的代码感到困惑...首先,byte[] data = new byte[0];没有任何用处,因为您稍后会覆盖它。其次,您正在创建new RandomAccessFile()try-catch 的外部。第三,您似乎将0字节长度传递给randomAccessFile.read(buffer, offset, length). 如果您对其中任何一个有意义,请发表评论以澄清。

如果您查看 Java 测试文件,他们有一个可以参考的示例:https ://github.com/google/flatbuffers/blob/master/tests/JavaTest.java#L30

尝试这样的事情:

*注意:我没有编译这段代码。但它应该足够相似以解决您的问题。

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());
于 2016-01-20T00:42:00.987 回答