“BufferedReader.ready”与“while(BufferedReader.readLine()!=null)”相比
对于java我是个新手。我想从 java 启动的进程中读取标准输出。我在谷歌搜索中得到了以下代码:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(args);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready()){
System.out.println(br.readLine());
}
但是,此代码不会打印进程(例如 ls)应该产生的输出(顺便说一句,我在 Linux 上,openJDK 1.6)
但是如果我将 while 循环更改为:
String line;
while((line = br.readLine())!=null){
System.out.println(line);
}
它按预期工作。
前面的代码有什么问题?根据java api doc所说,我认为它们是相似的。
I am a novice when it comes to java. I wanted to read the stdout from a process started in java. I got the following code upon a google search:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(args);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready()){
System.out.println(br.readLine());
}
However, this code does not print the output that the process (say, ls) is supposed to produce (btw, I am on Linux, openJDK 1.6)
But if I change the while loop to:
String line;
while((line = br.readLine())!=null){
System.out.println(line);
}
it works as expected.
What is the problem with the previous code? According to what the java api doc said, I thought they were similar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在上一个循环中,您只是在就绪状态下循环,而不是从流中读取任何字节。
In the previous loop, you're simply looping on the ready state, not reading any bytes from the stream.
当您到达
ready()
测试时,该命令尚未产生任何输出,并且返回false
,立即结束循环。您的第二个代码之所以有效,是因为
readLine()
调用会阻塞,直到读取整行为止。如果没有进一步的控制,此类代码的输出是不可预测的,因为它取决于命令产生的输出量以及完成所需的时间。这是一个非常简单的场景,因此它在大多数情况下都有效,但它不是一个通常可以应用的解决方案。
When you reach the
ready()
test, the command hasn't produced any output yet and it returnsfalse
, immediately ending the loop.Your second code works because the
readLine()
call blocks until it reads an entire line. Without further control, the output of such a code is unpredictable since it depends on the amount of output produced by the command and the time it takes to complete.This is a very simple scenario so it works most of the times but it is not a solution than can generally be applied.