使用Java ProcessBuilder执行Piped命令 [英] Using Java ProcessBuilder to Execute a Piped Command
本文介绍了使用Java ProcessBuilder执行Piped命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用Java的 ProcessBuilder
Class来执行一个有管道的命令。例如:
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执行Piped命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文