0

I am working on client-server sending and receiving of files/images. I use inputstream from a Socket.

Is this code

byte[] sizeAr = new byte[4];
int num = inputStream.read();
sizeAr = ByteBuffer.allocate(4).putInt(num).array();
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();

same as this code

byte[] sizeAr = new byte[4];
inputStream.read(sizeAr);
int size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();

1 Answers1

1

Is this code [...] same as this code?

No.


The first one does not make much sense to me:

  1. allocates a 4 byte array (for no reason?)
  2. reads a single byte from the stream
  3. 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
  4. 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:

  1. allocates a 4 byte array
  2. 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)
  3. 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 
Harald K
  • 26,314
  • 7
  • 65
  • 111