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.

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:

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.