要用java检测网络资源是否可用,我们可以采用以下两种方法:
一种方法是调用ping命令,通用对返回数据进行分析,来探测网络资源的可用性;
这种方法有一个缺点:就是许多网络资源是不允许被ping的,从而针对这类资源无法探测。
java代码
- package com.test;
-
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.LineNumberReader;
-
- public class PingTest {
-
-
-
-
-
- public static void main(String[] args) throws IOException {
- String address="www.javawind.net";
-
- Process process = Runtime.getRuntime().exec("ping "+address);
- InputStreamReader r = new InputStreamReader(process.getInputStream());
- LineNumberReader returnData = new LineNumberReader(r);
-
- String returnMsg="";
- String line = "";
- while ((line = returnData.readLine()) != null) {
- System.out.println(line);
- returnMsg += line;
- }
-
- if(returnMsg.indexOf("100% loss")!=-1){
- System.out.println("与 " +address +" 连接不畅通.");
- }
- else{
- System.out.println("与 " +address +" 连接畅通.");
- }
-
- }
- }
执行结果:
Pinging www.javawind.net [219.129.239.184] with 32 bytes of data:
Reply from 219.129.239.184: bytes=32 time=48ms TTL=115
Reply from 219.129.239.184: bytes=32 time=50ms TTL=115
Reply from 219.129.239.184: bytes=32 time=47ms TTL=115
Reply from 219.129.239.184: bytes=32 time=48ms TTL=115
Ping statistics for 219.129.239.184:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 47ms, Maximum = 50ms, Average = 48ms
与 www.javawind.net 连接畅通.