UNIX中JAVA执行命令
在使用java编写程序时候,我们可能需要执行shell命令,怎么办呢?看下面的例子:
import java.io.IOException;
public class ExecDemo {
static void doExec1() throws IOException {
// use pipes and I/O redirection
// but without using a shell
Runtime runtime = Runtime.getRuntime();
runtime.exec("ls | wc >out1");
}
static void doExec2() throws IOException {
// invoke a shell and give command to it
Runtime runtime = Runtime.getRuntime();
String[] args =
new String[]{"sh", "-c", "ls | wc >out2"};
Process p = runtime.exec(args);
}
public static void main(String[] args) throws IOException {
doExec1();
doExec2();
}
}
doExec1()不会正常执行,doExec2()可以正常执行。下面原文节选:
The problem with doExec1 is that Runtime.exec invokes actual executable binary programs. Syntax such as | and > are part of a particular command processor, and are only understood by that processor. ls is executed, but the rest of the shell command is not. However, doExec2 succeeds because it invokes a command processor or shell (sh), and gives the shell the input containing the | and > characters. Note that Runtime.exec could have been invoked with a single string argument like this:
"sh -c 'ls | wc >out2'"

