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 and classes for text data, especially non-ASCII data.

/* Note that as a general rule on most platforms characters
are only sent to 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.  */


public class Echo {

  public static void main(String[] args) {  
    try {
    catch (IOException 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 =;
      // -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; 


Previous | Next | Top | Cafe au Lait

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