Using read() to read one character at a time from console input

By: Jagan  

To read a character from a BufferedReader, use read( ). One form of the read() 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":

// Use a BufferedReader to read characters from the console.
class BRRead {
public static void main(String args[])
throws IOException
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(;
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char);
} while(c != 'q');

Here is a sample run:

Enter characters, 'q' to quit.

This output may look a little different from what you expected, because is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read( ) particularly valuable for interactive, console input.

Archived Comments

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial