我正在从终端运行我的 Java 程序,我试图在我的代码中使用 linux 命令来计算某个目录中的文件数;除了这个命令,我已经设法获得所有其他命令的输出。
我的命令是: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:
最佳答案
要执行管道,您必须调用一个 shell,然后在该 shell 中运行您的命令。
Process p = new ProcessBuilder().command("bash", "-c", command).start();
bash
调用 shell 来执行您的命令,-c
表示命令是从字符串中读取的。因此,您不必在 ProcessBuilder
中将命令作为数组发送。
但是如果你想使用运行时
那么
String[] cmd = {"bash" , "-c" , command};
Process p = Runtime.getRuntime().exec(cmd);
关于Java程序没有从终端获得输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156422/