8.4. The Standard Streams

Your operating system will typically define three standard streams that are accessible through members of the System class in Java:

  • A standard input stream that usually corresponds to the keyboard by default. This is encapsulated by the in member of the System class and is of type InputStream.

  • A standard output stream that corresponds to output on the command line. This is encapsulated by the out member of the System class and is of type PrintStream.

  • A standard error output stream for error messages that usually maps to the command-line output by default. This is encapsulated by the err member of the System class and is also of type PrintStream.

You can reassign any of these to another stream within a Java application. The System class provides the static methods setIn(), setOut(), and setErr() for this purpose. The setIn() method requires an argument of type InputStream that specifies the new source of standard input. The other two methods expect an argument of type PrintStream.

Since the standard input stream is of type InputStream, you are not exactly overwhelmed by the capabilities for reading data from the keyboard in Java. Basically, you can read a byte or an array of bytes using a read() method as standard, and that's it. If you want more than that, reading integers, or decimal values, or strings as keyboard input, you're on your own. Let's see what you can do to remedy that.

8.4.1. Getting Data from the Keyboard

To get sensible input from the keyboard, ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.