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

  }

 

posted @ 2019-06-26 14:48  大数据从业者FelixZh  阅读(685)  评论(0编辑  收藏  举报