Reading bytes of data

The basic read() method of the InputStream class reads a single unsigned byte of data and returns the int value of the unsigned byte. This is a number between 0 and 255. If the end of stream is encountered, it returns -1 instead; and you can use this as a flag to watch for the end of stream.

public abstract int read() throws IOException

Here's a simple program that echoes back what the user types at the command line. The byte is cast to its equivalent in the ISO Latin-1 character set before being printed. This program does not properly handle Unicode. In general, input and output streams do not properly handle Unicode data. Therefore you should use them only for raw data and use the java.io.Reader and java.io.Writer classes for text data, especially non-ASCII data.

/* Note that as a general rule on most platforms characters
are only sent to System.in a line at a time, not as each character
is typed. This allows the user to backspace over mistakes and 
correct them.  Java does not allow you to put the console into
"raw" mode.  */

import java.io.*;


public class Echo {

  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) {
      // Notice that although a byte is read, an int
      // with value between 0 and 255 is returned.
      // Then this is converted to an ISO Latin-1 char 
      // in the same range before being printed.   
      int i = in.read();
      // -1 is returned to indicate the end of stream
      if (i == -1) break;
        
      // without the cast a numeric string like "65"
      // would be printed instead of the character "A"
      char c = (char) i; 
      System.out.print(c);    
    }
    System.out.println();  
  
  }

}

Previous | Next | Top | Cafe au Lait

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