Java程序没有从终端输出

时间:2016-08-25 23:53:14

标签: java linux terminal

我正在从终端运行我的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:

1 个答案:

答案 0 :(得分:2)

要执行管道,您必须调用shell,然后在该shell中运行命令。

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

bash调用shell来执行命令,-c表示从字符串中读取命令。因此,您不必将命令作为数组发送到ProcessBuilder

但是如果你想使用Runtime那么

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

注意:您可以检查ProcessBuilder here和功能here优于Runtime

的优势