2016-08-25 138 views
1

我正在終端運行我的Java程序,我正在嘗試使用我的代碼中的linux命令來計算特定目錄中的文件數量;我已經設法得到所有其他命令的輸出,但這一個。Java程序沒有從終端獲取輸出

我的命令是:ls somePath/*.xml | wc -l

當我在我的代碼運行我的命令,看來它沒有任何輸出,但是當我在終端上運行完全相同的命令,它工作得很好,實際輸出的數量該目錄中的xml文件。

這裏是我的代碼:

private String executeTerminalCommand(String command) { 
    String s, lastOutput = ""; 
    Process p; 
    try { 
     p = Runtime.getRuntime().exec(command); 
     BufferedReader br = new BufferedReader(
       new InputStreamReader(p.getInputStream())); 
     System.out.println("Executing command: " + command); 
     while ((s = br.readLine()) != null){//it appears that it never enters this loop since I never see anything outputted 
      System.out.println(s); 
      lastOutput = s; 
     } 
     p.waitFor(); 
     p.destroy(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return lastOutput;//returns empty string "" 
} 

更新代碼瓦特/輸出

private String executeTerminalCommand(String command) { 
     String s, lastOutput = ""; 
     try { 
      Process p = new ProcessBuilder().command("/bin/bash", "-c", command).inheritIO().start();   
      //Process p = Runtime.getRuntime().exec(command); 
      BufferedReader br = new BufferedReader(
        new InputStreamReader(p.getInputStream())); 
      System.out.println("Executing command: " + command); 
      while ((s = br.readLine()) != null){ 
       System.out.println("OUTPUT: " + s); 
       lastOutput = s; 
      } 
      System.out.println("Done with command------------------------"); 
      p.waitFor(); 
      p.destroy(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     System.out.println("LAST OUTPUT IS: " + lastOutput); 
     return lastOutput; 
    } 

輸出:

Executing command: find my/path -empty -type f | wc -l 
Done with command------------------------ 
1 
LAST OUTPUT IS: 
+0

也許嘗試使用的ProcessBuilder和做'pb.redirectErrorStream(真);' –

+0

試試這個命令:'Process p = new ProcessBuilder()。command(「bash」,「-c」,「ls somePath/*。xml | wc -l」)。inheritIO().start(); ' –

+0

謝謝你們,但不幸最近那些不適合我。 –

回答

2

要執行的管道,你要調用一個shell ,然後在該shell中運行你的命令。

Process p = new ProcessBuilder().command("bash", "-c", command).start(); 

bash調用一個殼以執行命令,並-c裝置命令從串讀出。因此,您不必在ProcessBuilder中將該命令作爲數組發送。

但是,如果你想使用Runtime然後

String[] cmd = {"bash" , "-c" , command}; 
Process p = Runtime.getRuntime().exec(cmd); 

注:可以檢查ProcessBuilderhere優勢和特點here超過Runtime

+1

使用'ProcessBuilder'和'Runtime'看到答案是很好的。大多數答案建議使用'ProcessBuilder'並回答'ProcessBuilder'中的代碼。它確實有幫助。謝謝! – SkrewEverything

相關問題