readline()在Java中返回null [英] readline() returns null in Java
问题描述
我正在尝试在Java程序中读取标准输入.我期望一系列数字后跟换行符,例如:
I'm trying to read the stdin in my Java program. I'm expecting a series of numbers followed by newlines, like:
6
9
1
当通过eclipse内置控制台提供输入时,一切都会顺利进行.但是在使用Windows命令行时,程序将打印:
When providing the input through the eclipse built-in console, everything goes well. But when using the Windows command line, the program prints:
Received '6'.
Received 'null'.
Invalid input. Terminating. (This line is written by another function that does an Integer.parseint()).
我的代码是:
static String readLineFromStdIn(){
try{
java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String input = new String();
input = stdin.readLine();
System.out.println("Received '" + input + "'");
return(input);
}catch (java.io.IOException e) {
System.out.println(e);
}
return "This should not have happened";
}
有任何线索吗?
推荐答案
获得 null
表示相关的 Reader
对象达到了EOF(文件末尾),换句话说,他们无法再获得标准输入.现在,您的代码中明显的问题是:
That you get a null
indicates that the relevant Reader
objects reached an EOF (end of file), or in other words that they can't get any more standard input. Now the obvious issues with your code are:
- 对
readLineFromStdIn()
的每个方法调用都会创建一个 newBufferedReader
. - 每个这样的
BufferedReader
都将相互竞争,以获取System.in
中相同的共享输入 - 而且这些
BufferedReader
对象都没有被正确关闭,因此您的程序每次调用readLineFromStdIn()
都会泄漏I/O资源.
- Each method call to
readLineFromStdIn()
will create a newBufferedReader
. - Each such
BufferedReader
will be "competing" with each other for the same, shared input fromSystem.in
- And none of these
BufferedReader
objects are ever properly closed, so your program leaks I/O resources with each call toreadLineFromStdIn()
.
解决方案是对 readLineFromStdIn()
的每次调用使用单个共享的 BufferedReader
对象.
The solution is to use a single shared BufferedReader
object for each invocation of readLineFromStdIn()
.
这篇关于readline()在Java中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!