EOFException in my Java code

As other posts in stackoverflow have already explained, an EOFException is thrown when the end of the stream is reached unexpectedly. I have a method that converts an array of bytes to a long number. This byte array is the uint64_t number that I extracted by my java binding from the database in C. I know the problems with uint64_t and dropping to long numbers (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 don’t understand, why can I get this exception? I did not tell myself the length of the byte array, but I just pass the byte array to ByteArrayInputStream, so theoretically I should not get such an exception, I think.

(Please forgive me if the solution is obvious)

+3
2

bytearray, 8

+2

, null 8 .

ByteArrayInputStream stream = new ByteArrayInputStream(new byte[]{});
DataInputStream di = new DataInputStream(stream);
long number=-2;
try {
   number = di.readLong();
} catch (Exception e) {
   e.printStackTrace();
}
+2

Source: https://habr.com/ru/post/1757658/


All Articles