Counting the Available Bytes

It’s sometimes convenient to know how many bytes are available to 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 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 e) {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 e) {System.err.println("Couldn't read from System.in!");}

This works well if you’re only 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 only create a new array 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; ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.