0

I am shelling to an external windows program which updates its progress by repeatedly pushing new lines to the error stream.

The command prompt looks something like this when it's running:

10% done
10% done
11% done

and so forth.

I'm having some success capturing this in my java application thusly:

Process process = Runtime.getRuntime().exec("my little command");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while((s = stdError.readLine())!=null)
{
    System.out.println(s);                  
}

Unfortunately, as you may have guessed, there's a bit of a problem. The stdError.readLine() blocks until there are +- 4000 bytes in the error stream, and only then prints each line out in quick session, before it hangs again.

I've tried changing the BufferedReader buffer size, and using stdError.read(char [] cbuf, int off, int len)with a small length, to no avail.

How do I fix this hanging issue?

Thanks in advance :)

eye_mew
  • 8,855
  • 7
  • 30
  • 50

1 Answers1

1

The stdError.readLine() blocks until there are +- 4000 bytes in the error stream

No it doesn't. It returns as soon as there is a line to be read.

What is happening is that the source process is buffering its output, evidently into 4096-byte chunks. There's nothing you can do about it at the Java end.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Interesting, how is it then that in the actual command prompt, it is continuously printing? – eye_mew May 18 '14 at 03:40
  • Because `stdio` isn't buffered when the output is a terminal. – user207421 May 18 '14 at 03:58
  • The thing is, I'm convinced there is a way, since another closed source program exists (written in c++, if that's relevant) which definitely shells to the program in question, and is able to provide a fluid progress updates. – eye_mew May 18 '14 at 04:16
  • So that program calls `fflush(stderr),` or maybe does whatever it is that disables the buffering, and yours doesn't. – user207421 May 18 '14 at 05:24