Java程序没有从终端获得输出

标签 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:

最佳答案

要执行管道,您必须调用一个 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);

注意:您可以查看ProcessBuilder的优点here和功能 here运行时

关于Java程序没有从终端获得输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156422/

相关文章:

python - 安装anaconda后Linux终端问题

java - 如何在将子节点添加到父节点Java之前检测循环

java - Jersey 客户端和 CXF 混淆(多部分问题)

java - Lombok @SuperBuilder 不带参数

c++ - 在 64 位 Linux 上编译 32 位 Qt - fatal error : gnu/lib-names-32. h

linux - 在 Linux 中使用 FFMPEG 覆盖 TS 流文件

audio - 如何使我在Ubuntu 16.04上的声音再次起作用? (虚拟输出问题)

java - 格式错误的 URLException : unknown protocol: android

linux - 为什么允许修改argv[0]?

linux - 如何从bz2文件中提取数据而不解压文件