1

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);
}
user1971455
  • 413
  • 1
  • 7
  • 16

2 Answers2

2

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

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.

Michael
  • 34,873
  • 17
  • 75
  • 109
  • thanks. I realized there would only ever be about 10 lines in the buffer before i got to it again so ijust did this:int c = 0; while ((str = marsyasInput.readLine()) != null && c < 20) c++; – user1971455 Apr 14 '13 at 01:15
0
while (true){
  if ((s = myInput.readLine()) != null) {
    System.out.println(s);
  }

This code doesn't make any sense. If readLine() returns null, it is the end of the stream, and the only sensible course is to close the stream and exit the reading loop.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • the end of the stream will never come because the process is continuous. That's why I just want to grab the newest entry, like a LIFO container. – user1971455 Apr 14 '13 at 16:30