2017-10-16 203 views
1

我試圖執行它看起來像Java和exec命令 - 管多個命令

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

試試這個:

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