经常需要在Java中调用其它的脚本(shell,cmd), 以前都用:
Runtime r = Runtime.getSystemRuntime();
r.exec("whatever you want to run");
但是有时侯其运行结果是不可预期的,带来很多麻烦。从java 5.0以后,引入了ProcessBuilder to create operating system processes:
String cmd = "cd ../.. ; ls -l"; // this is the command to execute in the Unix shell
cmd ="cd ~/kaven/Tools/DART ; sh start_dart.sh";
// create a process for the shell
ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
pb.redirectErrorStream(true); // use this to capture messages sent to stderr
Process shell = pb.start();
InputStream shellIn = shell.getInputStream(); // this captures the output from the command
int shellExitStatus = shell.waitFor(); // wait for the shell to finish and get the return code
// at this point you can process the output issued by the command
// for instance, this reads the output and writes it to System.out:
int c;
while ((c = shellIn.read()) != -1) {
System.out.write(c);
}
// close the stream
try {
shellIn.close();
}
catch (IOException ignoreMe)
{}
System.out.print(" *** End *** "+shellExitStatus);
System.out.println(pb.command());
System.out.println(pb.directory());
System.out.println(pb.environment());
System.out.println(System.getenv());
System.out.println(System.getProperties());