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

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 | Cafe con Leche

Copyright 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 28, 2000