Parse out time portion from ping results in Java

后端 未结 2 546
情话喂你
情话喂你 2021-01-15 08:32

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?

相关标签:
2条回答
  • 2021-01-15 08:43

    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"));
    
    0 讨论(0)
  • 2021-01-15 09:06

    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.

    0 讨论(0)
提交回复
热议问题