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) {
  
    try {
      echo(System.in);
    }
    catch (IOException ex) {
      System.err.println(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 = in.read(b);
        if (result == -1) break;
        String s = new String(b);
        System.out.print(s); 
      } // end if   
    } // end while
  
  }

}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 19, 2005