简体   繁体   English

BufferedReader readline 如何在连续程序中工作?

[英]How does BufferedReader readline work in a continous program?

So I know I can use readline to get the program output line by line but if I use a while loop所以我知道我可以使用 readline 逐行获取程序 output 但如果我使用 while 循环

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

But this freezes my program until the external process finishes giving output.但这会冻结我的程序,直到外部进程完成提供 output。 I want to listen to the output as the external process gives it.我想听 output 作为外部进程给它。 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.我尝试使用 read() 但它也会冻结我的程序直到结束。 How can I read the output, whatever is available and then do my processing?我如何阅读 output,无论是可用的,然后进行我的处理? and then go back to read output again?然后 go 再次读取 output ?

You can use a separate thread to read the input stream.您可以使用单独的线程来读取输入 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:一种方法是将Callable任务提交给执行程序:

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> processOutput = executor.submit(() -> {
           // 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.您可以检查该值现在是否可用,或者等待该值出现超时等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM