JAVA调用系统命令:python、shell等
实际项目开发场景中,可能会用到java项目调用系统命令的需求,如调用python或者shell脚本
可以参考如下例子,例子来源于ambari源码:
\ambari\ambari-server\src\main\java\org\apache\ambari\server\security\CertificateManager.java
/** * Runs os command * * @return command execution exit code */ protected int runCommand(String command) { String line = null; Process process = null; BufferedReader br= null; try { process = Runtime.getRuntime().exec(command); br = new BufferedReader(new InputStreamReader( process.getInputStream(), Charset.forName("UTF8"))); while ((line = br.readLine()) != null) { LOG.info(line); } try { process.waitFor(); ShellCommandUtil.logOpenSslExitCode(command, process.exitValue()); return process.exitValue(); //command is executed } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return -1;//some exception occurred }
欢迎关注微信公众号:大数据从业者