2012-10-21 60 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