JAVA调用系统命令:python、shell等

python

实际项目开发场景中,可能会用到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

}

以上是 JAVA调用系统命令:python、shell等 的全部内容, 来源链接: utcz.com/z/387912.html

回到顶部