Programming Tutorials

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

By: Jagan in Java Tutorials on 2007-09-08  

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.
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.");
        // read characters
        do {
            c = (char) br.read();
            System.out.println(c);
        } while (c != 'q');
    }
}

Here is a sample run:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q

This output may look a little different from what you expected, because System.in 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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)