經常需要在Java中調用其它的指令碼(shell,cmd), 以前都用:
Runtime r = Runtime.getSystemRuntime();<br />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<br />cmd ="cd ~/kaven/Tools/DART ; sh start_dart.sh";<br />// create a process for the shell<br />ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);<br />pb.redirectErrorStream(true); // use this to capture messages sent to stderr</p><p>Process shell = pb.start();<br />InputStream shellIn = shell.getInputStream(); // this captures the output from the command<br />int shellExitStatus = shell.waitFor(); // wait for the shell to finish and get the return code</p><p>// at this point you can process the output issued by the command<br />// for instance, this reads the output and writes it to System.out:<br />int c;<br />while ((c = shellIn.read()) != -1) {<br />System.out.write(c);<br />}<br />// close the stream<br />try {<br />shellIn.close();<br />}<br />catch (IOException ignoreMe)<br />{}<br />System.out.print(" *** End *** "+shellExitStatus);</p><p>System.out.println(pb.command());<br />System.out.println(pb.directory());<br />System.out.println(pb.environment());<br />System.out.println(System.getenv());<br />System.out.println(System.getProperties());