// 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.
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
As you can see, it returns a String object.
The following program demonstrates BufferedReader and the readLine( ) method;
the program reads and displays lines of text until you enter the word "stop":
// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home