使用Java ProcessBuilder执行管道命令

时间:2022-01-27 20:47:53

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. Is there any way to accomplish this?

即使该命令在命令行中运行良好,我也无法让ProcessBuilder执行将其输出重定向到另一个的命令。有没有办法实现这个目标?

2 个解决方案

#1


48  

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中运行命令。

#2


5  

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”的标准输入。

#1


48  

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中运行命令。

#2


5  

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”的标准输入。