我在我的 java 程序中从命令行执行一些命令,它似乎不允许我使用“grep”?我已经通过删除“grep”部分对此进行了测试,命令运行得很好!
我的代码不起作用:
String serviceL = "someService";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list | grep " + serviceL);
有效的代码:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list");
这是为什么?是否有某种正确的方法或解决方法?我知道我可以只解析整个输出,但我会发现从命令行完成这一切会更容易。谢谢。
最佳答案
管道(如重定向,或 >
)是 shell 的一个功能,因此直接从 Java 执行它是行不通的。您需要执行以下操作:
/bin/sh -c "your | piped | commands | here"
在 -c
(引号)之后指定的命令行(包括管道)内执行 shell 进程。
所以,这是在我的 Linux 操作系统上运行的示例代码。
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
String[] cmd = { "/bin/sh", "-c", "ps aux | grep skype" };
Process proc = rt.exec(cmd);
BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
}
在这里,我正在提取所有“Skype”进程并打印进程输入流的内容。
关于Java 运行时进程不会 "Grep",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7825762/