EOFException in my Java Code
As other posts here at stackoverflow has already explained, the EOFException occurs when the end of the stream is reached unexpectedly. I have a method, which converts a byte array into a long number. This byte array is an uint64_t number which I retrieved over my java binding from a database in C. I do know the problems with uint64_t and casting to long numbers (t开发者_StackOverflowhe signed bit).
Here is my method:
public long castByteArrayToLong(byte[] bb){
ByteArrayInputStream stream = new ByteArrayInputStream(bb);
DataInputStream di = new DataInputStream(stream);
long number=-2;
try {
number = di.readLong();
} catch (Exception e) {
e.printStackTrace();
}
return number;
}
This method sometimes(!) throws this Exception:
java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:180)
at java.io.DataInputStream.readLong(DataInputStream.java:399)
at TreeManager.castByteArrayToLong(TreeManager.java:191)
at TreeManager.test2(TreeManager.java:442)
at TreeManager.main(TreeManager.java:72)
What I do not understand is why can I get that Exception? I did not specify myself the length of the byte array, but I just pass the byte array to the ByteArrayInputStream, so theoretically I shouldn't get an such exception, I think.
(Please forgive me, if the solution is obviously)
check the bytearray if it really has 8 bytes and is not null
An empty array, null
array or array with less than 8 bytes causes the exception. Try the following code
ByteArrayInputStream stream = new ByteArrayInputStream(new byte[]{});
DataInputStream di = new DataInputStream(stream);
long number=-2;
try {
number = di.readLong();
} catch (Exception e) {
e.printStackTrace();
}
精彩评论