7.3.1 Echo Revisited

The following example demonstrates how input is read from the console and printed back. Any I/O errors are caught and sent to the standard error stream. In this example, all the standard streams are used:

Here is the code.

import java.io.*;

public class Echo {

  public static void main (String[] args) {
    
    DataInputStream consoleIn = new DataInputStream(System.in);
    String line = "not null";

    while( ! line.equals("")) {
      try {
	line = consoleIn.readLine();
	System.out.println(line);
      } catch (IOException e) {
	System.err.println(e);
	break;
      }
    }
  }
}

There are several points to note.

  1. We make from the raw input stream System.in a DataInputStream with the line
    DataInputStream consoleIn = new DataInputStream(System.in);
    This more refined subclass DataInputStream offers the method readLine() apart from the basic read().
  2. We choose to let the program terminate if an empty line is entered.
  3. Input and output can lead often to problems (files are thrown away, disk full, etc). Hence many methods will generate an IOExceptions, e.g. the readLine method is encapsulated in a try-catch construct.
  4. both out and err are instances of PrintStream, which is a subclass of OutputStream. PrintStream offers the method println, which is more or less the converse of readLine.