本文介绍了如何使管道与 Runtime.exec() 一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

String commandf = "ls /etc | grep release";

try {

    // Execute the command and wait for it to complete
    Process child = Runtime.getRuntime().exec(commandf);
    child.waitFor();

    // Print the first 16 bytes of its output
    InputStream i = child.getInputStream();
    byte[] b = new byte[16];
    i.read(b, 0, b.length);
    System.out.println(new String(b));

} catch (IOException e) {
    e.printStackTrace();
    System.exit(-1);
}

程序的输出是:

/etc:
adduser.co

当然,当我从 shell 运行时,它按预期工作:

When I run from the shell, of course, it works as expected:

poundifdef@parker:~/rabbit_test$ ls /etc | grep release
lsb-release

互联网告诉我,由于管道行为不是跨平台的,在生产 Java 的 Java 工厂工作的聪明人不能保证管道工作.

The internets tell me that, due to the fact that pipe behavior isn't cross-platform, the brilliant minds who work in the Java factory producing Java can't guarantee that pipes work.

我该怎么做?

我不会使用 Java 结构而不是 grepsed 来完成所有的解析,因为如果我想更改语言,我将被迫用那种语言重写我的解析代码,这是完全不行的.

I am not going to do all of my parsing using Java constructs rather than grep and sed, because if I want to change the language, I'll be forced to re-write my parsing code in that language, which is totally a no-go.

如何让 Java 在调用 shell 命令时进行管道和重定向?

How can I make Java do piping and redirection when calling shell commands?

推荐答案

编写脚本,然后执行脚本而不是单独的命令.

Write a script, and execute the script instead of separate commands.

Pipe 是 shell 的一部分,因此您也可以执行以下操作:

Pipe is a part of the shell, so you can also do something like this:

String[] cmd = {
"/bin/sh",
"-c",
"ls /etc | grep release"
};

Process p = Runtime.getRuntime().exec(cmd);

这篇关于如何使管道与 Runtime.exec() 一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:59