我正在終端運行我的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:
也許嘗試使用的ProcessBuilder和做'pb.redirectErrorStream(真);' –
試試這個命令:'Process p = new ProcessBuilder()。command(「bash」,「-c」,「ls somePath/*。xml | wc -l」)。inheritIO().start(); ' –
謝謝你們,但不幸最近那些不適合我。 –