本文介绍了使用 Java ProcessBuilder 执行管道命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Java 的 ProcessBuilder
类来执行一个包含管道的命令.例如:
I'm trying to use Java's ProcessBuilder
class to execute a command that has a pipe in it. For example:
ls -l | grep foo
但是,我收到一个错误:
However, I get an error:
ls: |: no such file or directory
关注:
ls: grep: no such file or directory
即使该命令从命令行完美运行,我也无法让 ProcessBuilder
执行将其输出重定向到另一个的命令.
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 b = new ProcessBuilder("/bin/sh", "-c", "ls -l| grep foo");
要执行管道,您必须调用一个 shell,然后在该 shell 中运行您的命令.
To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.
这篇关于使用 Java ProcessBuilder 执行管道命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!