“BufferedReader.ready”与“while(BufferedReader.readLine()!=null)”相比

发布于 2024-11-29 14:32:48 字数 614 浏览 0 评论 0原文

对于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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私野 2024-12-06 14:32:48

在上一个循环中,您只是在就绪状态下循环,而不是从流中读取任何字节。

In the previous loop, you're simply looping on the ready state, not reading any bytes from the stream.

神仙妹妹 2024-12-06 14:32:48

当您到达 ready() 测试时,该命令尚未产生任何输出,并且返回 false,立即结束循环。

您的第二个代码之所以有效,是因为 readLine() 调用会阻塞,直到读取整行为止。如果没有进一步的控制,此类代码的输出是不可预测的,因为它取决于命令产生的输出量以及完成所需的时间。

这是一个非常简单的场景,因此它在大多数情况下都有效,但它不是一个通常可以应用的解决方案。

When you reach the ready() test, the command hasn't produced any output yet and it returns false, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文