2

我设法修改了一个程序来 ping 对等计算机并获取 ping 计数。如何实时解析time = ?msping 计数结果?

代码:

 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”写入文本文件?

我正在寻求提示,谢谢。

4

2 回答 2

3

试试这个:

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

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

于 2013-02-18T13:26:52.893 回答
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"));
于 2013-02-18T13:07:22.077 回答