Java和exec命令 - 管道多个命令

时间:2017-10-16 21:05:21

标签: java command

我正在尝试执行看起来像

的命令

pass = executeCommand("/usr/bin/openssl rand -base64 8 | tr -d '+' | cut -c1-8")

但在这种情况下pass值为空。当我离开时没有用管道输送

pass = executeCommand("/usr/bin/openssl rand -base64 8")

一切正常

方法executeCommand看起来像

private static String executeCommand(String command) throws Exception {

      StringBuffer output = new StringBuffer();

      Process p;
      try {
         p = Runtime.getRuntime().exec(command);
         p.waitFor();
         BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

         String line = "";
         while ((line = reader.readLine()) != null) {
            output.append(line + "\n");
         }

      }
      catch (Exception e) {
         e.printStackTrace();
         throw new Exception("Could not generate password : " + e.getMessage());
      }

      return output.toString().trim();

   }

有关如何使该管道版本正常工作的任何建议吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

String[] COMPOSED_COMMAND = {
        "/bin/bash",
        "-c",
        "/usr/bin/openssl rand -base64 8 | tr -d '+' | cut -c1-8",};
Process p = Runtime.getRuntime().exec(COMPOSED_COMMAND);