加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:35:57 所属栏目:Java 来源:网络整理
导读:我正在调用通过管道连接的命令行程序.所有这些都可以在 Linux上运行. 我的方法: protected String execCommand(String command) throws IOException { String line = null; if (command.length() 0) { Process child = Runtime.getRuntime().exec(command);
我正在调用通过管道连接的命令行程序.所有这些都可以在 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;
}

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

cat /proc/cpuinfo | wc -l

或这个:

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

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

解决方法

管道(如重定向或>)是shell的一个功能,因此直接从Java执行将不起作用.你需要做一些事情:
/bin/sh -c "your | piped | commands | here"

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

另请注意,您必须同时使用stdout和stderr,否则您生成的进程将阻止等待您的进程使用输出(或错误).更多信息here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读