本文主要是介绍Java_代码执行ping命令,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Java代码执行Ping命令:
import android.content.Context;import com.umeng.analytics.MobclickAgent;import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.Map;/*** Created by Ricky on 2016/10/13.*/
public class PingIPUtils implements Runnable {private Context mContext;private String ipstr = "";private Map map;private int runCount = 0;private String returnParam = "";public PingIPUtils(String ipstr, Context mContext ,Map map){this.mContext = mContext;this.ipstr = ipstr;this.map = map;}@Overridepublic void run() {pingRun("www.baidu.com");pingRun(ipstr);}public void pingRun(String address){runCount++ ;Process process = null;try {process = Runtime.getRuntime().exec("ping -c 1 -w 5 "+address);} catch (IOException e) {System.out.println("ping Exception......");e.printStackTrace();}InputStreamReader r = new InputStreamReader(process.getInputStream(), Charset.forName("GBK"));LineNumberReader returnData = new LineNumberReader(r);String returnMessage="";String line = "";try {while ((line = returnData.readLine()) != null) {returnMessage = returnMessage + line + "\n";}} catch (IOException e) {e.printStackTrace();}System.out.println(returnMessage);if("".equals(returnParam)){returnParam = "ping 地址:" + address;}else{returnParam = returnParam + " " + "ping 地址:" + address;}String[] lines = returnMessage.split("\n");String time;for (String line1 : lines) {if (line1.contains("time=")){int index = line1.indexOf("time=");int end = line1.indexOf("ms") + 2;time = line1.substring(index + "time=".length(),end);returnParam = returnParam + "time: " + time;System.out.println(returnParam);}else if(line1.contains("时间=")){int index = line1.indexOf("时间=");int end = line1.indexOf("ms") + 2;time = line1.substring(index + "时间=".length(),end);returnParam = returnParam + "时间: " + time;System.out.println(returnParam);}else{returnParam = returnParam + line1;System.out.println(returnParam);continue;}}if(runCount >= 2){map.put("pingIP",returnParam);MobclickAgent.onEvent(mContext , "TimeOut", map);System.out.println("最后参数:" + returnParam);}}
}
开启线程调用:
new Thread(new PingIPUtils("182.92.172.193", context , map)).start();
这篇关于Java_代码执行ping命令的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!