2014-01-27 122 views
0

我已經看過幾個應該這樣做的例子,並且就核心機制而言,我和他人之間沒有任何區別。這裏是我的代碼:不顯示控制檯輸出的Java程序

public class Console 
{ 
    public static void main(String[] args) throws IOException, InterruptedException{ 
     Runtime rt = Runtime.getRuntime(); 
     Process ps; 
     System.out.println("Gathering available network data...");  

     String cmd[] = {"ifconfig","|","grep","'inet addr:'"}; 
     ps = rt.exec(cmd); 
     getOutput(cmd,ps); 
    } 
    public static String getOutput(String[] c, Process p) throws IOException, InterruptedException 
    { 
     Process ps = p; 
     String output=""; 
     BufferedReader readerStd = new BufferedReader(new InputStreamReader(ps.getInputStream())); 
     BufferedReader readerErr = new BufferedReader(new InputStreamReader(ps.getInputStream())); 

     String line = null; 
     System.out.println("Result:"); 
     while ((line = readerStd.readLine()) != null) { 
      System.out.println(line); 
      output+=line+"\n"; 
     } 

     if((line = readerErr.readLine()) != null) 
     { 
      System.out.println("------ Std Err -------"); 
      System.out.println(line); 
      while ((line = readerErr.readLine()) != null) 
      { 
       System.out.println(line); 
      } 
     } 
     return output; 
    } 
} 

預期輸出是:

Gathering available network data... 
Result: 
      inet addr:10.40.2.234 Bcast:10.40.2.255 Mask:255.255.255.0 
      inet addr:127.0.0.1 Mask:255.0.0.0 

實際的輸出是:

Gathering available network data... 
Result: 

我在做什麼錯?

回答

0

管道操作員|被解釋爲外殼,因此不構成命令本身的一部分。此外,該命令需要出現在單個令牌以防止grep的段被分別進行評估:

String cmd[] = { "bash", "-c", "ifconfig |grep 'inet addr:'" }; 
+0

嗯,這確實給我一些輸出,但只爲ifconfig和忽略表達的整個grep的部分。絕對是一種改進,但不是我需要的。 – cHam

+0

實際上不需要標記命令 - 請參閱更新 – Reimeus