使用 Java ProcessBuilder 执行管道命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3776195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Java ProcessBuilder to Execute a Piped Command
提问by user455889
I'm trying to use Java's ProcessBuilder
class to execute a command that has a pipe in it. For example:
我正在尝试使用 Java 的ProcessBuilder
类来执行一个包含管道的命令。例如:
ls -l | grep foo
However, I get an error:
但是,我收到一个错误:
ls: |: no such file or directory
Followed by:
其次是:
ls: grep: no such file or directory
Even though that command works perfectly from the command line, I can not get ProcessBuilder
to execute a command that redirects its output to another.
即使该命令从命令行完美运行,我也无法ProcessBuilder
执行将其输出重定向到另一个命令的命令。
Is there any way to accomplish this?
有什么办法可以做到这一点吗?
回答by Jon Skeet
The simplest way is to invoke the shell with the command line as the parameter. After all, it's the shell which is interpreting "|" to mean "pipe the data between two processes".
最简单的方法是使用命令行作为参数调用shell。毕竟,解释“|”的是shell 意思是“在两个进程之间传输数据”。
Alternatively, you could launch each process separately, and read from the standard output of "ls -l", writing the data to the standard input of "grep" in your example.
或者,您可以单独启动每个进程,并从“ls -l”的标准输出中读取,将数据写入示例中“grep”的标准输入。
回答by dogbane
This should work:
这应该有效:
ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l| grep foo");
To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.
要执行管道,您必须调用一个 shell,然后在该 shell 中运行您的命令。