我怎么能得到ping的时间?

时间:2015-11-12 07:31:02

标签: android ping

我使用此代码ping网站google.com

    public String ping(String url) {
       String str = "";
       try {
           Process process = Runtime.getRuntime().exec(
                   "/system/bin/ping -c 1 " + url);
           BufferedReader reader = new BufferedReader(new InputStreamReader(
                   process.getInputStream()));

           int i;
           char[] buffer = new char[4096];
           StringBuffer output = new StringBuffer();

           while ((i = reader.read(buffer)) > 0)
               output.append(buffer, 0, i);
           reader.close();

           // body.append(output.toString()+"\n");
           str = output.toString();
           Log.d("str", str);
       }
       catch (IOException e) {
           // body.append("Error\n");
           e.printStackTrace();
       }
       return str;
   }

log-cat输出如下:

11-12 07:23:34.028: D/str(1399): PING www.google.com (216.58.209.196) 56(84) bytes of data. 
11-12 07:23:34.028: D/str(1399): 64 bytes from bud02s22-in-f4.1e100.net (216.58.209.196): icmp_seq=1 ttl=48
**time=149 ms** 
11-12 07:23:34.028: D/str(1399): --- www.google.com ping statistics --- 
11-12 07:23:34.028: D/str(1399): 1 packets transmitted, 1 received, 0% packet loss, time 0ms 
11-12 07:23:34.028: D/str(1399): rtt min/avg/max/mdev = 149.750/149.750/149.750/0.000 ms

让任何人知道如何才能获得"时间= 149毫秒"值? 提前谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用正则表达式:

/.*time=([0-9]+)\s(ms).*/

您想要的信息位于两个捕获组中。我推荐正则表达式的原因是因为如果你想要一些其他的信息,你可以很容易地扩展它。

sed上面的示例(d包含您的字符串):

prakhar@inS4n3 /tmp $ cat d| sed -r 's/.*?time=([0-9]+)\s(ms).*/\1 \2/'
149 ms

以下是如何在java中使用上述内容:http://www.tutorialspoint.com/java/java_regular_expressions.htm

答案 1 :(得分:0)

使用String. indexOf (String subString, int start)方法查找str变量中的所有“time =”子字符串,并在每个“time =”子字符串后获取数字。 或者使用ReqularExpression read here

答案 2 :(得分:0)

在你的情况下试试这个:

    try {
            Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 " + url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            int i;
            char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();

            while ((i = reader.read(buffer)) > 0)
                output.append(buffer, 0, i);
            reader.close();

            // body.append(output.toString()+"\n");
            str = output.toString();

            if (str.contentEquals("time=")) {
                str = str.substring(str.indexOf("time="), str.length());
                Log.d("str", str);
            }
        }