阅读286 返回首页    go 阿里云 go 技术社区[云栖]


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

  上一篇:go 定义返回函数指针的函数
  下一篇:go 凯撒加密+Base64--打造安全又高效的加密算法