Is this code [...] same as this code?
No.
The first one does not make much sense to me:
- allocates a 4 byte array (for no reason?)
- reads a single byte from the stream
- creates a new 4 byte buffer,
- puts the byte read in the previous line into the buffer as an int,
- gets the backing array of the buffer, replacing the array in the first line
- wraps the array from the previous buffer in a new byte buffer,
- converts it to an int buffer
- gets the int from this buffer, and assigns this int to
size
Basically, this is a very convoluted an inefficient way of doing
int size = inputStream.read();
I don't think this is what you want. :-)
The second one makes more sense:
- allocates a 4 byte array
- reads up to 4 bytes from the input stream into the array (note that you should check the return value of
read(byte[])
, to get the number of bytes read, it may be less than the size of your array)
- wraps the array in a buffer,
- converts it to an int buffer
- gets the value as an int and assigns it to
size
This version will read a full 32 bit int value into size
, which is probably what you want. However, step 2 is not safe, as you may read less than 4 bytes as mentioned.
Probably, a better way would be to use something like:
DataInput dataInput = new DataInputStream(inputStream);
int size = dataInput.readInt(); // Will read exactly 4 bytes or throw EOFException