我设法修改了程序以ping对等计算机并获得ping计数。如何从ping计数结果中实时解析time = ?ms

码:

 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


我需要声明一个变量,然后使用BufferedReader将“ time =?ms”写入文本文件吗?

我正在寻找提示,谢谢。

最佳答案

尝试这个:

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


从捕获的模式中输出毫秒值。

关于java - 从Java中的ping结果解析出时间部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14937019/

10-14 12:20