Java Reference
In-Depth Information
Reading Standard Input
Problem
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). Yet another is piping the output of one pro-
gram directly to the input of another, a very common operation among Unix users and quite
valuable on other platforms, such as Windows, that support this operation.
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
Most desktop platforms support the 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 stand-
ard error stream without having to open any files or make any other special arrangements.
Java continues this tradition and enshrines it in the
System
class. The static variables
Sys-
tem.in
,
System.out
, and
System.err
are connected to the three operating system streams
before your program begins execution (an application is free to reassign these; see
Discus-
its methods. For example, to read one byte from the standard input, you call the read method
of
System.in
, which returns the byte in an
int
variable:
int
int
b
=
System
.
in
.
read
( );