Java Streams  «Prev  Next»

Lesson 4Counting the available bytes
ObjectiveWrite program that uses byte array buffer/ available() method

Counting available Java bytes

Write a program that uses a byte array buffer and the available() method to efficiently copy data from System.in to System.out.
It is 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.

public int available() 
throws IOException

To find out how many bytes are available to be read, you could write the following code:
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 the above code. There may be more bytes available than there is space in the array to hold them. One common idiom is to size the array according to the number that 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 the multiple arrays is excessive.
You should probably reuse the array, but check the availability against the space in the array first.
When no bytes are available to be read, available() returns 0.

Available Bytes - Exercise

Click the Exercise link below to write a program that uses
  1. a byte array buffer,
  2. an InputStream,
  3. the available() method, and
  4. the System.out.println() method
to write a more efficient program that copies data from System.in to System.out.
Available Bytes - Exercise