请解释为什么这种奇怪的行为发生在案例3中但不是案例4中.
public class InputBufferedReader {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//1-start
//read one character
System.out.println("enter input: ");
int b= br.read();
System.out.println(b);
//end
//2-start
//read a string
System.out.println("enter input string: ");
String a = br.readLine();
System.out.println(a);
//end
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你BufferedReader
用的InputStreamReader
是System.in
.在BufferedReader
使用read()
从方法InputStreamReader
,以从标准输入流中读取的数据System.in
.现在让我们来看看这个read()
方法的API .
[...]此方法将阻塞,直到输入数据可用,检测到流的末尾或抛出异常.
在此上下文中,阻止装置等待用户通过控制台使用Enter键确认输入数据.
考虑到这一点,让我们检查你的案例.
1. int b= br.read();
没有输入任何内容,因此此方法会阻塞,直到用户键入内容然后打印第一个字符的ascci值.
2. String a = br.readLine();
没有输入任何内容,因此此方法会阻塞,直到用户键入内容然后打印整行.
3.
int b= br.read();
Run Code Online (Sandbox Code Playgroud)
让图像用户a
使用Enter键键入 确认,表示输入是a\n
.现在read()
读取第一个字符a
.
String a = br.readLine();
Run Code Online (Sandbox Code Playgroud)
此read()
调用不会阻止并请求用户输入,因为还有未使用的输入\n
.所以readLine()
会读\n
.
4.
String a = br.readLine();
Run Code Online (Sandbox Code Playgroud)
要求用户输入通过Enter键确认的输入.整行将被阅读.
int b= br.read();
Run Code Online (Sandbox Code Playgroud)
没有未消耗的数据,因为readLine()
已经读取了包括\n
字符在内的整行.所以这个read()
调用块和用户被要求输入.