To read a character from 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 character from the console until the user types a "q"
Program : Read.java
import java.io.*;
class Read
{
public static void main(String arg[]) throws IOException
{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter character 'q' to quit ");
do
{
c=(char)br.read();
System.out.println(c);
}
while(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
Output
G:\java\io>javac Read.java
G:\java\io>java Read
Enter character 'q' to quit
A B C D q
A
B
C
D
q
0 comments:
Post a Comment