Here is the javadoc of available
method and this is what it says:
Returns the number of bytes that can be read without blocking.
So, it does not return the total number of bytes
present in your array/read, it returns the number of bytes
it can read before getting blocked. So, it returning 0 is a valid scenario.
Now, let's have a look at javadoc of ObjectInputStream, here is the brief explanation:
Non-object reads which exceed the end of the allotted data will
reflect the end of data in the same way that they would indicate the
end of the stream: bytewise reads will return -1 as the byte read or
number of bytes read, and primitive reads will throw EOFExceptions. If
there is no corresponding writeObject method, then the end of default
serialized data marks the end of the allotted data.
What you are trying to do in your code is to read
the primitive data (or reading without WriteObject
method), as it is not valid data (for ObjectInputStream
) read
will always return -1. And I was able to reproduce EOFException
just by calling readObject
method.
I then tried writing/reading a new object and tested available
method call, have a look at the below snippet:
byte[] buffer = new byte[]{-84, -19, 0, 5};
System.out.println("\n" + Arrays.toString(buffer) + "\n");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
System.out.println("buffer.length = " + buffer.length + "\nnew ByteArrayInputStream(buffer).available() is: " + new ByteArrayInputStream(buffer).available());
ObjectInputStream input = new ObjectInputStream(byteArrayInputStream);
System.out.println("input.available(): " + input.available());
// System.out.println(input.readObject()); //Uncomment to see EOFException
Date date = new Date();
System.out.println(date);
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteArrayOut);
out.writeObject(date);
byte[] bytes = byteArrayOut.toByteArray();
input = new ObjectInputStream(new ByteArrayInputStream(bytes));
System.out.println(input.available());
System.out.println(input.readObject());
The code reads
the already written object and prints the value. Please note that even though it reads the object correctly and prints the same object, available
method still returns 0. So, I would recomment not to rely too much on available
because of it's misleading name :)