O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading Standard Input

Problem

Despite Rusty’s comments, you really do need to read from the standard input, or console. One reason is that simple test programs are often console-driven. Another is that some programs naturally require a lot of interaction with the user and you want something faster than a GUI (consider an interactive mathematics or statistical exploration program).

Solution

To read bytes, wrap a BufferedInputStream( ) around System.in. For the more common case of reading text, use an InputStreamReader and a BufferedReader .

Discussion

On most non-Macintosh desktop platforms, there is a notion of standard input -- a keyboard, a file, or the output from another program -- and standard output -- a terminal window, a printer, a file on disk, or the input to yet another program. Most such systems also support a standard error output, so that error messages can be seen by the user even if the standard output is being redirected. When programs on these platforms start up, the three streams are preassigned to particular platform-dependent handles, or file descriptors. The net result is that ordinary programs on these operating systems can read the standard input or write to the standard output or standard error stream without having to open any files or make any other special arrangements.

Java continues this tradition, and enshrines it in the Java Standard Edition’s System class. The static variables System.in , System.out, and System.err are connected to the three operating ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required