Java Reference
In-Depth Information
Table 10-4
The Methods Defined by
OutputStream
Reading Console Input
Originally, the only way to perform console input was to use a byte stream, and much Java
code still uses the byte streams exclusively. Today, you can use byte or character streams.
For commercial code, the preferred method of reading console input is to use a character-
oriented stream. Doing so makes your program easier to internationalize and easier to
maintain.
It is also more convenient to operate directly on characters rather than converting back
and forth between characters and bytes. However, for sample programs, simple utility pro-
grams for your own use, and applications that deal with raw keyboard input, using the byte
streams is acceptable. For this reason, console I/O using byte streams is examined here.
Because
System.in
is an instance of
InputStream
, you automatically have access to
the methods defined by
InputStream
. Unfortunately,
InputStream
defines only one input
method,
read( )
, which reads bytes. There are three versions of
read( )
, which are shown
here:
int read( ) throws IOException
int read(byte
data
[ ]) throws IOException
int read(byte
data
[ ], int
start
, int
max
) throws IOException
from the keyboard (from
System.in
). It returns -1 when the end of the stream is en-
countered. The second version reads bytes from the input stream and puts them into
data
until either the array is full, the end of stream is reached, or an error occurs. It returns
the number of bytes read, or -1 when the end of the stream is encountered. The third ver-