Java Reference
In-Depth Information
To obtain an
InputStreamReader
object that is linked to
System.in
, use the constructor
shown next:
InputStreamReader(InputStream
inputStream
)
Since
System.in
refers to an object of type
InputStream
, it can be used for
inputStream
.
Next, using the object produced by
InputStreamReader
, construct a
BufferedReader
using the constructor shown here:
BufferedReader(Reader
inputReader
)
Here,
inputReader
is the stream that is linked to the instance of
BufferedReader
being cre-
ated. Putting it all together, the following line of code creates a
BufferedReader
that is
connected to the keyboard.
After this statement executes,
br
will be a character-based stream that is linked to the con-
sole through
System.in
.
Reading Characters
Characters can be read from
System.in
using the
read( )
method defined by
BufferedReader
in much the same way as they were read using byte streams. Here are
three versions of
read( )
supported by
BufferedReader
.
int read( ) throws IOException
int read(char
data
[ ]) throws IOException
int read(char
data
[ ], int start, int
max
) throws IOException
The first version of
read( )
reads a single Unicode character. It returns -1 when the end
of the stream is reached. The second version reads characters 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 characters read or -1 at the end of the stream. The third
version reads input into
data
beginning at the location specified by
start
. Up to
max
charac-
ters are stored. It returns the number of characters read or -1 when the end of the stream is
encountered. All throw an
IOException
on error. When reading from
System.in
, pressing
ENTER
generates an end-of-stream condition.
The following program demonstrates
read( )
by reading characters from the console un-
til the user types a period. Notice that any I/O exceptions that might be generated are simply