这是我用于读取平面缓冲区文件的代码。我总是得到一个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();
}
}
答案 0 :(得分:1)
我对您的代码感到困惑......首先,byte[] data = new byte[0];
没有任何用处,因为您稍后会覆盖它。其次,您在try-catch外创建new RandomAccessFile()
。第三,您似乎将0
的字节长度传递给randomAccessFile.read(buffer, offset, length)
。如果您对其中任何一个有意义,请发表评论以澄清。
如果你看一下Java Test文件,他们有一个你可以参考的例子: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());