java进程,getInputStream,仅读取最新行 [英] java Process, getInputStream, read newest line only

查看:83
本文介绍了java进程,getInputStream,仅读取最新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的while循环中,我只想读取Process p的输出中的最新行,而忽略循环休眠时进入缓冲区的其他任何内容.我该怎么办?

In the while loop below I want to read only the newest line from Process p's output, ignoring anything else that entered the buffer while the loop was sleeping. How do I do that?

String s;
Runtime r = Runtime.getRuntime();
Process p = r.exec("SomeContinuousProgram");
myInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

while (true){
  if ((s = myInput.readLine()) != null) {
    System.out.println(s);
  }
Thread.sleep(sleep);
}

推荐答案

您不能跳到"从流程中写入的最新行.您必须阅读前面的所有行.

You can't "skip" to the newest line that was written from the process. You have to read all lines that came before it.

将程序分成2个线程.主线程将从 BufferedReader 中读取并跟踪最新的行.另一个线程将进入睡眠状态,然后显示最新的行.

Split the program into 2 threads. The main thread will read from the BufferedReader and will keep track of what the newest line is. The other thread will sleep, and then display the newest line.

这篇关于java进程,getInputStream,仅读取最新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆