Alfe
Alfe

Reputation: 59566

Simplest way of calling external program without stream capture

What is the simplest way to call an external program from Java without capturing the stdin/stdout/stderr streams? A simple way for calling an external program is sth like

Runtime.getRuntime().exec(new String[] { "/bin/ls", "-la" });

But this captures the output of this program, so to just have it on the console I need to wrap it in some monster like this:

p = Runtime.getRuntime().exec(new String[] { "/bin/ls", "-la" });
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

But of course if I am not interested in these streams (here only stdout was passed through), it is nonsense to first redirect them to me and then just pass them on.

Is there a simpler way to achieve this? I guess I just want to call an external program without stream redirection.

Upvotes: 2

Views: 161

Answers (1)

Alfe
Alfe

Reputation: 59566

Since version 1.7 the class ProcessBuilder knows a method inheritIO() which can be called prior to creating a process to achieve this:

ProcessBuilder pb = new ProcessBuilder(new String[] { "ls", "-la" });
pb.inheritIO();
Process p = pb.start();
exitValue = p.waitFor();

A version like this for 1.6 does not seem to be available, though. (Remarks are always welcome.)

A hint to this information was originally provided by a Marko Topolnik.

Upvotes: 0

Related Questions