How to execute shell script in Java?
經常需要在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());
最後更新:2017-04-02 04:00:25