In Java, console input is accomplished by reading from System.in. To obtain a character-
based stream that is attached to the console, wrap System.in in a BufferedReader object.
BufferedReader supports a buffered input stream. Its most commonly used constructor
is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters. To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will
be using is
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as
an integer value. It returns 1 when the end of the stream is encountered. As you can see,
­
it can throw an IOException.
The following program demonstrates read( ) by reading characters from the console
until the user types a "q." Notice that any I/O exceptions that might be generated are
simply thrown out of main( ). Such an approach is common when reading from the console,
but you can handle these types of errors yourself, if you chose.
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home