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();
random.nextBytes(simulatedSource);
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 = inputStream.read(target, bytesExtracted, bytesToExtract);            
    if (temporaryBytesReadCount == -1)
    {
        break;
    }
    for (byte b : target)
    {
        byteList.add(b);
    }
    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.

Advertisements

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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: