2011-10-19 48 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