class="java" name="code">package cn.com.songjy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Ping {
public static void main(String[] args) throws IOException {
System.out.println(ping("127.0.0.1", 1));
System.out.println("************************************");
System.out.println(ping("www.baidu.com", 35));
}
/**
*
* @param target_name
* IP地址或域名
* @param out_time
* 超时间隔,单位为毫秒
* @return
* @throws IOException
*/
public static boolean ping(String target_name, int out_time)
throws IOException {
Runtime runtime = Runtime.getRuntime();
String ping_command = "ping " + target_name + " -w " + out_time;
System.out.println("命令格式:" + ping_command);
Process process = runtime.exec(ping_command);
if (null == process)
return false;
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream(), "GBK"));// windows下编码默认是GBK,Linux是UTF-8
String line = null;
while (null != (line = bufferedReader.readLine())) {
System.out.println(line);
if (line.startsWith("Reply from"))
return true;
if (line.startsWith("来自"))
return true;
}
bufferedReader.close();
return false;
}
}
/* 这里只是简单检测是否能通,如果还需要更详细信息可查看ping命令的介绍 */
效果图如下:
java 调用shell命令
java使用dos命令创建文件夹
大小: 25.9 KB
查看图片附件