2013-02-18 40 views
2

我設法修改程序以ping對等計算機並獲得ping計數。我如何從ping計數結果中實時解析出time = ?ms從ping中解析出時間部分結果爲Java

代碼:

public static void main(String[] args) { 

    String ip = "192.168.1.1 -n 10"; 
    String pingResult = ""; 

    String pingCmd = "ping " + ip; 

    try{ 

     Runtime r = Runtime.getRuntime(); 
     Process p = r.exec(pingCmd); 

     BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) { 
      System.out.println(inputLine); 
      pingResult += inputLine; 
     } 
     in.close(); 
    } catch(Exception e) { 
     System.out.println(e); 
    } 
} 

輸出:

Reply from 192.168.1.1: bytes=32 time=2ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=4ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=20ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=9ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=3ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=2ms TTL=64 
Reply from 192.168.1.1: bytes=32 time=3ms TTL=64 

Ping statistics for 192.168.1.1: 
    Packets: Sent = 10, Received = 10, Lost = 0 (0% loss), 
Approximate round trip times in milli-seconds: 
    Minimum = 2ms, Maximum = 20ms, Average = 4ms 

上午我需要聲明一個變量,並寫出了 「?時間= MS」 成文本文件使用的BufferedReader?

我在尋找提示,謝謝。

回答

2

試試這個:

Pattern pattern = Pattern.compile("time=(\\d+)ms"); 
Matcher m = null; 
while ((inputLine = in.readLine()) != null) { 
    m = pattern.matcher(inputLine); 
    if (m.find()) { 
     System.out.println(m.group(1)); 
    } 
} 

它從捕獲的模式中輸出毫秒值。

+0

它的工作原理,很多... 現在我要根據rtt/times來調整JMF編碼器,真的很感激... – 2013-02-18 14:15:01

1

你可以使用indexOf

pingResult = pingResult.substring(pingResult.indexOf("time=")); 

然後取出TTL

pingResult = pingResult.substring(0, pingResult.indexOf("TTL")); 

因此,最終代碼:

Runtime r = Runtime.getRuntime(); 
Process p = r.exec(pingCmd); 

BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
String inputLine; 
while ((inputLine = in.readLine()) != null) { 
    System.out.println(inputLine); 
    pingResult += inputLine; 
} 
in.close(); 
pingResult = pingResult.substring(pingResult.indexOf("time=")).substring(0, pingResult.indexOf("TTL")); 
+0

非常感謝,我現在試試吧...... – 2013-02-18 13:11:46

+0

它的工作原理,非常感謝...但是,輸出結果對我來說有點難以繼續我的工作......分享和你的教學,真的很... – 2013-02-18 14:17:05