Various ways to read bytes from an input stream in Java

Say you want to fill a byte array from a source, e.g. a from a randomly simulated data of 50 bytes like the following:

byte[] simulatedSource = new byte[50];
Random random = new Random();
InputStream inputStream = new ByteArrayInputStream(simulatedSource);  

At a basic level we can read each byte one by one from the input stream as follows:

byte[] input = new byte[100];

        int byteRead =;
        if (byteRead == -1) break;
        input[i] = (byte)byteRead;
    } catch (IOException ex)
        //exception handling ignored
} returns an integer which must be converted into a byte. If the read method returns -1 then we know that there’s nothing else coming from the input stream hence we can break the loop.

Reading an input stream byte by byte is not too efficient. The read() method has two overloads one of which accepts a byte array. The provided byte array is filled with the bytes extracted from the input stream. The number of bytes extracted depends on the target array size and how many bytes there are remaining in the input stream. The following example will read the random byte array of 50 elements in chunks of 20 and collect the chunks into an expandable byte list:

byte[] inputTwo = new byte[20];
List<Byte> byteList = new ArrayList<>();
int result = 0;
while (result > -1)
    result =;
    if (result > -1)
        for (byte b : inputTwo)

When is called the first time then inputTwo is populated with 20 bytes from the input stream and “result” is set to 20. The next iteration yields the same outcome: inputTwo is populated with the next 20 elements and result is 20. The third iteration is more interesting: result will be 10 as expected and input two will still be 20. The first 10 elements are the remaining 10 out of the 50 in total, the second half is the remainder from the second iteration. As a result “byteList” will have a size of 60 instead of the expected 50. This means that the input array is not automatically cleaned by the read method before filling it with bytes. Therefore the above code is not exactly what we want. Here’s a possible fix:

while (result > -1)
    result =;
    if (result > -1)

…we only read the relevant elements into the target list of bytes.

The second overload of the read method accepts a target array like above and two integer parameters. The first integer is an offset, i.e. at which position we should read from the input stream. The second integer is the length, i.e. how many elements we should read in total. The following example shows a possible usage:

int bytesExtracted = 0;
int bytesToExtract = 20;
byte[] inputThree = new byte[bytesToExtract];
while (bytesExtracted < bytesToExtract)
    int temporaryBytesReadCount =, bytesExtracted, bytesToExtract - bytesExtracted);
    if (temporaryBytesReadCount == -1)
    for (int i = 0; i < temporaryBytesReadCount; i++)

View all posts related to Java networking here.


About Andras Nemes

Leave a Reply


You are commenting using your account. Log Out / Change )

Twitter picture


Facebook photo


Google+ photo


Connecting to %s


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy


Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture


Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Cyber Matters


Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby


%d bloggers like this: