Check available number of bytes in an input stream in Java

In this post we saw how to read the bytes contained in an input stream. The most common way to achieve it is by way of one of the read methods. The overloaded version where we provide a target byte array, an offset and a total byte count to be read is probably used most often.

It can happen in real-life situations that we provide the total number of bytes to be extracted but those bytes have not yet “arrived”, i.e. are not yet available in the input stream. This can occur when reading the bytes from a slow network connection. The bytes will eventually be available. The read method will block the thread it’s running in while it is waiting for the bytes to be loaded.

In case you want to avoid this thread-blocking scenario you can check the number of bytes readily loadable from the input stream. The available() method returns the number of bytes that can be extracted from the stream without blocking the thread. Here’s an example:

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

int bytesToExtract = inputStream.available();
int bytesExtracted = 0;
byte[] target = new byte[bytesToExtract];
List<Byte> byteList = new ArrayList<>();
while (bytesExtracted < bytesToExtract)
    int temporaryBytesReadCount =, bytesExtracted, bytesToExtract);            
    if (temporaryBytesReadCount == -1)
    for (byte b : target)
    bytesToExtract = inputStream.available();
    target = new byte[bytesToExtract];

We check the number of bytes available from the stream before we enter the loop. Within the loop we read that many bytes from the input stream. We exit the loop in case we’ve reached the end of the stream, i.e. if read returns -1. We then add the elements into the byte array list. Finally we re-read the available number of bytes and rebuild the target array for the next iteration.

View all posts related to Java networking here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Facebook photo

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

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: