Parse out time portion from ping results in Java

独自空忆成欢 提交于 2019-12-01 08:11:17

问题


I managed to modify a program to ping peer computer and gets the ping counts. How can I parse out the time = ?ms from the ping count results, in real-time?

Code:

 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);
    }
}

Output:

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

Am I need to declare a variables and write the "time = ?ms" into a textfile using BufferedReader?

I am seeking for hints, thanks.


回答1:


Try this:

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));
    }
}

Which outputs the millisecond value from the captured patterns.




回答2:


You could use indexOf:

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

Then remove the TTL:

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

Therefore, the final code:

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"));


来源:https://stackoverflow.com/questions/14937019/parse-out-time-portion-from-ping-results-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!