【问题标题】:Java and exec command - pipe multiple commands [duplicate]Java和exec命令-管道多个命令[重复]
【发布时间】:2017-10-17 05:39:36
【问题描述】:

我正在尝试执行一个看起来像这样的命令

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();

   }

有什么建议可以让管道版本正常工作吗?

【问题讨论】:

    标签: java command


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 2017-06-03
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多