Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Thinking in Java
Prev Contents / Index Next

Reading from standard input

Following the standard I/O model, Java has, System.out, and System.err. Throughout this book, you’ve seen how to write to standard output using System.out, which is already prewrapped as a PrintStream object. System.err is likewise a PrintStream, but is a raw InputStream with no wrapping. This means that although you can use System.out and System.err right away, must be wrapped before you can read from it.

Typically, you’ll want to read input a line at a time using readLine( ), so you’ll want to wrap in a BufferedReader. To do this, you must convert to a Reader using InputStreamReader. Here’s an example that simply echoes each line that you type in:

// How to read from standard input.
// {RunByHand}

public class Echo {
  public static void main(String[] args)
  throws IOException {
    BufferedReader in = new BufferedReader(
      new InputStreamReader(;
    String s;
    while((s = in.readLine()) != null && s.length() != 0)
    // An empty line or Ctrl-Z terminates the program
} ///:~

The reason for the exception specification is that readLine( ) can throw an IOException. Note that should usually be buffered, as with most streams.
Thinking in Java
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire