Reputation: 127
I use this code to ping the website 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;
}
The log-cat output looks like that:
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
Have anyone and idea how I can just get the "time=149 ms" value? Thanks in advance!
Upvotes: 2
Views: 1342
Reputation: 2391
In your case try this:
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);
}
}
Upvotes: 0
Reputation: 379
use String. indexOf (String subString, int start) method to find all the "time=" substrings in the str variable, and get the digits after every "time=" substring. Or use ReqularExpression read here
Upvotes: 0
Reputation: 3409
You can use a regex:
/.*time=([0-9]+)\s(ms).*/
The information you want is in the two capturing groups. The reason I am recommending regex is because if you want some other information, you can easily extend this.
sed
example of above (d
contains your string):
prakhar@inS4n3 /tmp $ cat d| sed -r 's/.*?time=([0-9]+)\s(ms).*/\1 \2/'
149 ms
Here's how to use the above in java: http://www.tutorialspoint.com/java/java_regular_expressions.htm.
Upvotes: 1