How to make pipes work with Runtime.exec()?

poundifdef picture poundifdef · May 8, 2011 · Viewed 69.3k times · Source

Consider the following code:

String commandf = "ls /etc | grep release";

try {

    // Execute the command and wait for it to complete
    Process child = Runtime.getRuntime().exec(commandf);
    child.waitFor();

    // Print the first 16 bytes of its output
    InputStream i = child.getInputStream();
    byte[] b = new byte[16];
    i.read(b, 0, b.length); 
    System.out.println(new String(b));

} catch (IOException e) {
    e.printStackTrace();
    System.exit(-1);
}

The program's output is:

/etc:
adduser.co

When I run from the shell, of course, it works as expected:

poundifdef@parker:~/rabbit_test$ ls /etc | grep release
lsb-release

The internets tell me that, due to the fact that pipe behavior isn't cross-platform, the brilliant minds who work in the Java factory producing Java can't guarantee that pipes work.

How can I do this?

I am not going to do all of my parsing using Java constructs rather than grep and sed, because if I want to change the language, I'll be forced to re-write my parsing code in that language, which is totally a no-go.

How can I make Java do piping and redirection when calling shell commands?

Answer

Kaj picture Kaj · May 8, 2011

Write a script, and execute the script instead of separate commands.

Pipe is a part of the shell, so you can also do something like this:

String[] cmd = {
"/bin/sh",
"-c",
"ls /etc | grep release"
};

Process p = Runtime.getRuntime().exec(cmd);