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.

import java.io.*;


public class EfficientEcho {

  public static void main(String[] args) {
  
    echo(System.in);
  
  }
  
  public static void echo(InputStream in) {
  
    try {
      while (true) {
        int n = in.available();
        if (n > 0) {
          byte[] b = new byte[n];
          int result = in.read(b);
          if (result == -1) break;
          String s = new String(b);
          System.out.print(s); 
        } // end if   
      } // end while
    } // end try
    catch (IOException e) {
      System.err.println(e); 
    }
  
  }

}

Previous | Next | Top
Last Modified July 8, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu