Java exec()不返回管道连接命令的预期结果

Paw*_*wka 6 java linux bash awk command-line

我正在调用通过管道连接的命令行程序.所有这些都可以在Linux上运行.

我的方法:

protected String execCommand(String command) throws IOException {
    String line = null;
    if (command.length() > 0) {
        Process child = Runtime.getRuntime().exec(command);
        InputStream lsOut = child.getInputStream();
        InputStreamReader r = new InputStreamReader(lsOut);
        BufferedReader in = new BufferedReader(r);

        String readline = null;
        while ((readline = in.readLine()) != null) {
            line = line + readline;
        }
    }

    return line;
}
Run Code Online (Sandbox Code Playgroud)

如果我正在调用一些猫文件| grep asd,我得到了预期的结果.但并非所有命令都能正常工作.例如:

cat /proc/cpuinfo | wc -l
Run Code Online (Sandbox Code Playgroud)

或这个:

cat /proc/cpuinfo | grep "model name" | head -n 1 | awk -F":" '{print substr($2, 2, length($2))}
Run Code Online (Sandbox Code Playgroud)

该方法将返回null.我猜这个问题取决于输出格式化命令,如head,tail,wc等.我如何解决这个问题并获得输出的最终结果?

Bri*_*new 8

管道(如重定向或>)是shell的一个功能,因此直接从Java执行将不起作用.你需要做一些事情:

/bin/sh -c "your | piped | commands | here"
Run Code Online (Sandbox Code Playgroud)

它使用在-c(在引号中)之后指定的命令行(包括管道)执行shell进程.

还需要注意的是,你必须消耗stdoutstderr 并发,否则你的衍生进程将阻止等待你的过程中要消耗的输出(或错误).更多信息在这里.


Paw*_*wka 1

仍然没有找到使用 Runtime.exec 执行管道命令的正确解决方案,但找到了解决方法。我只是将这些脚本编写为单独的 bash 文件。然后 Runtime.exec 调用这些 bash 脚本并获得预期结果。