Java程序没有从终端获取输出 [英] Java program not getting output from terminal
问题描述
我正在从终端运行我的 Java 程序,我正在尝试使用我的代码中的 linux 命令来计算某个目录中的文件数量;我设法获得了除这个命令之外的所有其他命令的输出.
I am running my Java program from terminal and I am trying to count the number of files in a certain directory using a linux command in my code; I have managed to get output for all other commands but this one.
我的命令是:ls somePath/*.xml |wc -l
当我在我的代码中运行我的命令时,它似乎没有任何输出,但是当我在终端中运行完全相同的命令时,它工作得很好并且实际上输出了该目录中的 xml 文件数.
When I run my command in my code, it appears that it has nothing to output, yet when I run the same exact command in terminal it works just fine and actually outputs the number of xml files in that directory.
这是我的代码:
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 中运行您的命令.
To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.
Process p = new ProcessBuilder().command("bash", "-c", command).start();
bash
调用 shell 来执行您的命令,-c
表示从字符串中读取命令.因此,您不必将命令作为 ProcessBuilder
中的数组发送.
bash
invokes a shell to execute your command and -c
means commands are read from string. So, you don't have to send the command as an array in ProcessBuilder
.
但是如果你想使用 Runtime
那么
But if you want to use Runtime
then
String[] cmd = {"bash" , "-c" , command};
Process p = Runtime.getRuntime().exec(cmd);
注意:您可以在此处查看ProcessBuilder
的优势和功能此处超过运行时
Note: You can check advantages of ProcessBuilder
here and features here over Runtime
这篇关于Java程序没有从终端获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!