Counting the Available Bytes
It's sometimes convenient to know how many bytes can be read before you attempt to read them. The InputStream class's available( ) method tells you how many bytes you can read without blocking. It returns 0 if there's no data available to be read.
public int available( ) throws IOException
For example:
try { byte[] b = new byte[100]; int offset = 0; while (offset < b.length) { int a = System.in.available( ); int bytesRead = System.in.read(b, offset, a); if (bytesRead == -1) break; // end of stream offset += bytesRead; } catch (IOException ex) { System.err.println("Couldn't read from System.in!"); }
There's a potential bug in this code. There may be more bytes available than there's space in the array to hold them. One common idiom is to size the array according to the number available( ) returns, like this:
try { byte[] b = new byte[System.in.available( )]; System.in.read(b); } catch (IOException ex) { System.err.println("Couldn't read from System.in!"); }
This works well if you're going to perform a single read. For multiple reads, however, the overhead of creating multiple arrays is excessive. You should probably reuse the array and create a new array only if more bytes are available than will fit in the array.
The available( ) method in java.io.InputStream always returns 0. Subclasses are supposed to override it, but I've seen a few that don't. You may be able to read more bytes from the underlying stream without blocking than available( ) suggests; you just can't guarantee that you can. If this is a concern, place input in a separate thread so that blocked input doesn't block the rest of the program.