我的Java程序正在监听标准输入:
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bufReader = new BufferedReader(isReader);
while(true){
try {
String inputStr = null;
if((inputStr=bufReader.readLine()) != null) {
...
}
else {
System.out.println("inputStr is null");
}
}
catch (Exception e) {
...
}
}
现在,我想通过管道将输入从bash传递到这个程序。我尝试了以下几种方法:
echo "hi" | java -classpath ../src test.TestProgram
但它只是无限次地打印inputStr is null
。我做错了什么?
编辑1:更新问题以包含更多代码/上下文。
编辑2:
看起来我遇到了与此操作相同的问题:Command Line Pipe Input in Java
我如何修复程序,以便我可以通过管道输入测试,但正常运行程序将允许用户输入标准输入?
发布于 2011-04-20 10:13:13
修好了。在输入管道完成后,readLine()
一直返回null
,因此无限循环继续循环。
修复方法是在readLine()
返回null时中断无限循环。
发布于 2012-08-29 18:17:23
你有while(true)
,所以你会得到无限循环。
在循环中的某处添加break
是修复该问题的一种方法。但这不是一种好的风格,因为读者必须在循环中寻找,以找出它是否以及何时退出。
最好让您的while
语句清楚地显示退出条件是什么:
String inputStr = "";
while(inputStr != null) {
inputStr=bufReader.readLine();
if(inputStr != null) {
...
} else {
System.out.println("inputStr is null");
}
}
发布于 2014-04-25 00:05:21
我喜欢斯利姆的回答,只是我的处理方式有点不同。这是我用来逐行阅读文本流的基本模板。
try {
// Wrap the System.in inside BufferedReader
// But do not close it in a finally block, as we
// did no open System.in; enforcing the rule that
// he who opens it, closes it; leave the closing to the OS.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
// TODO: Handle input line
}
// Null was received, so loop was aborted.
} catch (IOException e) {
// TODO: Add error handler
}
如果我正在读取一个文件,我会稍微修改一下,以关闭文件,如下所示
try {
File file = new File("some_file.txt");
// Wrap the System.in inside BufferedReader
// But do not close it in a finally block, as we
// did no open System.in; enforcing the rule that
// he who opens it, closes it; leaves the closing to the OS.
BufferedReader in = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = in.readLine()) != null) {
// TODO: Handle input line
}
// Null was received, so loop was aborted.
} finally {
try {
in.close();
} catch (IOException e) {
}
}
} catch (IOException e) {
// TODO: Add error handler
}
https://stackoverflow.com/questions/5724646
复制相似问题