Home >Java >javaTutorial >Why Does Java's `Runtime.exec()` Produce Unexpected Results with Pipes?
Pipes and Runtime.exec() in Java
Consider the following Java code:
String commandf = "ls /etc | grep release"; try { Process child = Runtime.getRuntime().exec(commandf); child.waitFor(); 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
However, when run from the shell, it correctly displays:
lsb-release
Cross-Platform Pipe Behavior
As mentioned in the question, pipe behavior is not cross-platform. The Java creators cannot guarantee that pipes will work consistently across different platforms.
Alternative Solutions
To address this issue, consider the following options:
String[] cmd = { "/bin/sh", "-c", "ls /etc | grep release" }; Process p = Runtime.getRuntime().exec(cmd);
The above is the detailed content of Why Does Java's `Runtime.exec()` Produce Unexpected Results with Pipes?. For more information, please follow other related articles on the PHP Chinese website!