2011-10-19 45 views
5

我正在执行命令行在我的Java程序中的一些命令,它似乎不允许我使用“grep”?我已经通过删除“grep”部分来测试这个,并且命令运行的很好!Java运行时进程不会“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"); 

这是为什么?是否有某种正确的方法或解决方法?我知道我可以解析整个输出,但是我会发现从命令行执行所有操作更容易。谢谢。

回答

6

你正在尝试使用管道,这是shell的一个功能......而你没有使用shell;你直接执行chkconfig进程。

最简单的解决办法是给exec外壳,并将它做的一切:

Process proc = rt.exec("/bin/sh -c chkconfig --list | grep " + serviceL); 

话虽这么说......你为什么管道与grep?只要阅读chkconfig的输出结果并在java中进行匹配。

+0

没有理由,我无法在Java中匹配。我只是认为写出grep比分析输出要快。我对Linux比较新,所以我不知道grep是shell的一个功能。谢谢! – Max

+3

@Max:grep不是shell内建的,管道'|'是一个shell语法特性。 – ninjalj

8

管道(如重定向,或>)是shell的函数,因此直接从Java执行它不起作用。你需要做的是这样的:

/bin/sh -c "your | piped | commands | here" 

其命令行(包括管道)内执行shell进程的-c(引号)后确定。

所以,这里是一个示例代码,适用于我的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'进程并打印过程输入流的内容。

+0

美丽的解决方案! –

0

String [] commands = {“bash”,“-c”,“chkconfig --list | grep”+ serviceL}; 进程p = Runtime.getRuntime()。exec(commands);

或者如果你在linux环境下只使用grep4j