Counting the available bytes

The available() method tests how many bytes are ready to be read from the stream without blocking.

public int available() throws IOException

For example, the following program is a more efficient version of Echo that uses available() to test how many bytes are ready to be read, creates an array of exactly that size, reads the bytes into the array, then converts the array to a String and prints the String.


public class EfficientEcho {

  public static void main(String[] args) {
    try {
    catch (IOException ex) {
  public static void echo(InputStream in) throws IOException {

    while (true) {
      int n = in.available();
      if (n > 0) {
        byte[] b = new byte[n];
        int result =;
        if (result == -1) break;
        String s = new String(b);
      } // end if   
    } // end while


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2005 Elliotte Rusty Harold
Last Modified July 19, 2005