Re: IOException thrown by process: avoidable?
In article
<705241e2-649a-45df-b1e3-d8ad69f3e345@t13g2000yqt.googlegroups.com>,
Ron <bnoronb@gmail.com> wrote:
[...]
I think maybe the process finishes, the stream gets closed, my
java program attempts to read the next line of output and gets
the IOException. ?I think the timing has to be just right though,
because given the same command, I sometimes see the exception and
sometimes not. ?I also thought that maybe the process is not
outputing an EOF before exiting as a possible cause, but that
doesn't really explain why, for the same command, I sometimes get
the exception, and sometimes do not.
Looking closer at your initial example, I see that you are creating a
new ProcessBuilder and starting it to yield Process p. Then you start a
new Thread from which you read p's stdout and wait for p to complete.
Instead, shouldn't you do something more like this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PBTest {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("ls", ".");
pb.redirectErrorStream(true);
try {
Process p = pb.start();
String s;
// read from the process's combined stdout & stderr
BufferedReader stdout = new BufferedReader (
new InputStreamReader(p.getInputStream()));
while ((s = stdout.readLine()) != null) {
System.out.println(s);
}
System.out.println("Exit value: " + p.waitFor());
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
}
}
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>