views:

57

answers:

2

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 (the 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)

+2  A: 

check the bytearray if it really has 8 bytes and is not null

Nikolaus Gradwohl
thank you, that was indeed the problem
mkn
+2  A: 

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();
}
Manuel Selva
the problem was that the byte array I received from the database is sometimes not 8 bytes long, even though it should...
mkn