javaioobjectinputstreambytearrayinputstream

ByteArrayInputStream to ObjectInputStream disappeared


I've something that I don't understand, please help.

System.out.println("\n" + Arrays.toString(buffer) + "\n");
System.out.println("buffer.length = " + buffer.length + "\nnew ByteArrayInputStream(buffer).available() is: " + new ByteArrayInputStream(buffer).available());
ObjectInput input = new ObjectInputStream(new ByteArrayInputStream(buffer));
System.out.println("input.available(): " + input.available());

Its output is below:

[-84, -19, 0, 5]

buffer.length = 4
new ByteArrayInputStream(buffer).available() is: 4
input.available(): 0

I'm so confused why a byte array of 4 valid bytes, after putting into ObjectInputStream, it becomes zero.

Things I've tried:

  1. Initially, I was doubting my byte array was empty, but as you see, I printed out, its length is 4.
  2. Then I thought my byte might be invalid, so I printed out each byte, as you can see, those four bytes are all valid.

So, I'm lost why this is happening.

Please help, thanks a lot!


Solution

  • As the other answer mentioned, available only means the number of bytes you can read before blocking occurs.

    It is my guess, however, that you didn't follow the rules of the ObjectInputStream, which specify An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

    In other words, in order to actually read the data with an ObjectInputStream, you first must have written the data using an ObjectOutputStream of some kind. Here's an example showing this with the data you provided:

    byte[] buffer = new byte[]{-84,-19,0,5};
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream= new ObjectOutputStream(out);
    objectOutputStream.write(buffer);
    objectOutputStream.flush();
    
    ObjectInput input = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
    System.out.println("input.available(): " + input.available());
    System.out.println("input.readByte(): " + input.readByte());
    

    (I'll add that I very rarely work with IO in Java, so the above may not be best practice or have superfluous code.)