Check available number of bytes in an input stream in Java
November 6, 2017 Leave a comment
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.