I am a novice when it comes to java. I wanted to read the stdout from a process started in java. I got the following code upon a google search:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(args);
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while(br.ready()){
System.out.println(br.readLine());
}
However, this code does not print the output that the process (say, ls) is supposed to produce (btw, I am on Linux, openJDK 1.6)
But if I change the while loop to:
String line;
while((line = br.readLine())!=null){
System.out.println(line);
}
it works as expected.
What is the problem with the previous code? According to what the java api doc said, I thought they were similar.
In the previous loop, you’re simply looping on the ready state, not reading any bytes from the stream.