Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java -- How to read an unknown number of bytes from an inputStream (socket/socketServer)?

Looking to read in some bytes over a socket using an inputStream. The bytes sent by the server may be of variable quantity, and the client doesn't know in advance the length of the byte array. How may this be accomplished?


byte b[]; 
sock.getInputStream().read(b);

This causes a 'might not be initialized error' from the Net BzEAnSZ. Help.

like image 670
farm ostrich Avatar asked Apr 17 '11 01:04

farm ostrich


People also ask

How does InputStream read () method work?

read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255. If no byte is available because the end of the stream has been reached, the returned value is -1.

Why does the read method of the InputStream class return an int not a byte?

It returns an int because when the stream can no longer be read, it returns -1. If it returned a byte, then -1 could not be returned to indicate a lack of input because -1 is a valid byte.

What does InputStream read return?

Returns. the total number of bytes read into the buffer, or <code>-1</code> if there is no more data because the end of the stream has been reached.


2 Answers

You need to expand the buffer as needed, by reading in chunks of bytes, 1024 at a time as in this example code I wrote some time ago

    byte[] resultBuff = new byte[0];
    byte[] buff = new byte[1024];
    int k = -1;
    while((k = sock.getInputStream().read(buff, 0, buff.length)) > -1) {
        byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
        System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
        System.arraycopy(buff, 0, tbuff, resultBuff.length, k);  // copy current lot
        resultBuff = tbuff; // call the temp buffer as your result buff
    }
    System.out.println(resultBuff.length + " bytes read.");
    return resultBuff;
like image 172
d-live Avatar answered Oct 10 '22 01:10

d-live


Assuming the sender closes the stream at the end of the data:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buf = new byte[4096];
while(true) {
  int n = is.read(buf);
  if( n < 0 ) break;
  baos.write(buf,0,n);
}

byte data[] = baos.toByteArray();
like image 42
Vladimir Dyuzhev Avatar answered Oct 10 '22 03:10

Vladimir Dyuzhev