如何在连续的程序中使用 BufferedReader 的 readline 功能?

huangapple go评论75阅读模式
英文:

How does BufferedReader readline work in a continous program?

问题

所以我知道我可以使用readline逐行获取程序输出,但是如果我使用while循环

String l;
while ((l = input.readLine()) != null)
    rcv = rcv + l
return rcv;

但是这会导致我的程序冻结,直到外部进程完成输出。我希望能够在外部进程输出时就监听输出。外部程序可能需要很长时间才能退出。

我尝试使用read(),但它也会导致程序在结束之前冻结。我该如何读取任何可用的输出,然后进行处理?然后再继续读取输出?

英文:

So I know I can use readline to get the program output line by line but if I use a while loop

String l;
 while( (l=input.readLine()) != null)
    rcv = rcv + l
 return rcv;

But this freezes my program until the external process finishes giving output. I want to listen to the output as the external process gives it. It can take a long time for the external program to exit.

I tried using read() but it also freezes my program until the end. How can I read the output, whatever is available and then do my processing? and then go back to read output again?

答案1

得分: 0

你可以使用单独的线程来读取输入流。思路是阻塞操作应该发生在一个单独的线程中,这样你的应用程序主线程就不会被阻塞。

一种方法是将一个Callable任务提交给执行器(Executor):

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> processOutput = executor.submit(() -> {
   // 在这里编写读取流的代码
   String l, rcv;
   while ((l = input.readLine()) != null) { ... }
   return rcv;
});

这会返回一个"future",它是表示一个可能在未来某个时刻可用但当前可能不可用的值的方式。你可以检查该值现在是否可用,或者等待该值在未来某个时刻可用,还可以设置超时等。

英文:

You can use a separate thread to read the input stream. The idea is that the blocking operations should happen in a separate thread, so your application main thread is not blocked.

One way to do that is submitting a Callable task to an executor:

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future&lt;String&gt; processOutput = executor.submit(() -&gt; {
           // your code to read the stream goes here
           String l, rcv;
           while( (l=input.readLine()) != null) { ... }
           return rcv;
        });

This returns a "future" which is a way to represent a value that may not be available now but might be at some point in the future. You can check if the value is available now, or wait for the value to be present with a timeout, etc.

huangapple
  • 本文由 发表于 2020年4月8日 21:27:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/61101855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定