2012-10-21 57 views
3

Noobie在剛剛開始的java中,將不勝感激任何幫助。所以,我的代碼是這樣的,由於某種原因我不能得到的輸出work..I一直在坐了好幾個小時..在java中使用BufferedReader讀取終端命令的輸出

package askisi1; 

import java.net.*; 
import java.util.*; 
import java.lang.*; 
import java.io.*; 


public class Main{ 

public static void main(String[] args){ 

    try{ 

     String command = "ifconfig eth1 | grep -oP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'"; 
     Process child = Runtime.getRuntime().exec(command); 

     System.out.println("So far so good"); 
     BufferedReader r = new BufferedReader(new InputStreamReader(child.getInputStream())); 
     String s; 
     while ((s = r.readLine()) != null) { 
     System.out.println(s); 
     } 
     r.close(); 
     System.out.println("Continue.."); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 



} 
+0

這可能是有點複製到http://stackoverflow.com/questions/3159913/problem-從輸入流java-process-runtime-getruntime-exec-or-pr –

+0

你運行命令來確保它產生輸出嗎? – jozefg

+0

@WolfgangFahl我研究了你在發佈我的問題之前發佈的問題,但它看起來太複雜了,並且因爲我對ProcessBuilder不熟悉。感謝您指出它。 –

回答

2

Runtime.exec()需要一些額外的信息來執行的UNIX命令。

因此,假設我的以太網卡是lo0

String[] command = { 
        "/bin/sh", 
        "-c", 
        "ifconfig lo0 | grep -oP '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}'" 
      }; 
Process child = Runtime.getRuntime().exec(command); 
// following here your remaining unchanged code 

此打印:

So far so good 
127.0.0.1 
Continue.. 
+0

工作出色的謝謝! –

+0

@Stelsavva不客氣:) – Mik378