当前位置: 代码迷 >> J2SE >> 求帮忙写个程序解决思路
  详细解决方案

求帮忙写个程序解决思路

热度:41   发布时间:2016-04-24 00:40:54.0
求帮忙写个程序
我想一直去连一个IP,也就是PING那个IP地址,求帮忙写个程序一直PINT它,如果连同就打印连接成功,否则打印连接失败

------解决方案--------------------
public class CommandUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtil.class);

public static String exec(String command) {
LOGGER.info("开始执行命令: " + command);
String result = null;
try {
Process process = Runtime.getRuntime().exec(command);
if (process != null) {
result = getExecMessage(process);
// 输出执行记录详情
LOGGER.info(result);
process.destroy();
}
LOGGER.info("执行完毕!");
}
catch (Exception ex) {
LOGGER.error("执行shell命令出现异常, 详情:", ex);
}
return result;
}

public static String exec(String[] cmdarray) {
LOGGER.info("开始执行命令: " + ArrayUtil.toString(cmdarray, "\n"));
String result = null;
try {
Process process = Runtime.getRuntime().exec(cmdarray);
if (process != null) {
result = getExecMessage(process);
// 输出执行记录详情
LOGGER.info(result);
process.destroy();
}
LOGGER.info("执行完毕!");
}
catch (Exception ex) {
LOGGER.error("执行shell命令出现异常, 详情: ", ex);
}
return result;
}

public static String getExecMessage(Process process) {
BufferedReader stream = null;
StringBuilder result = new StringBuilder();
try {
stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = stream.readLine()) != null) {
result.append(line).append("\n");
NullUtil.toNull(line);
}
LOGGER.info(result.insert(0, "执行详情: ").toString());
// if (process.waitFor() != 0) {
// error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// while ((line = error.readLine()) != null) {
// buffer.append(line).append("\n");
// NullUtil.toNull(line);
// }
// }
}
catch (Exception ex) {
LOGGER.error("执行错误, 详情: ", ex);
}
finally {
if (stream != null) {
try {
stream.close();
}
catch (IOException e) {}
}
}
return result.toString();
}

public static void main(String[] args) {
System.out.println(exec("ping www.baidu.com"));
}

------解决方案--------------------
大致思路:通过java调用执行shell命令,对返回的结果进行解析,并且通过计算可得出流量。。。你可以百度一下吧
------解决方案--------------------
重点在Runtime.getRuntime().exec("ping xxx");
------解决方案--------------------
Java code
import java.io.IOException;import java.net.InetAddress;import java.util.concurrent.Executors;public class Pinger implements Runnable {    public static void main(String[] args) throws Exception {        Executors.newCachedThreadPool().submit(new Pinger("127.0.0.1", 3000));  }    private final String ip;  private final int timeout;  public Pinger(String ip, int timeout) {        this.ip = ip;    this.timeout = Math.max(1000, timeout);  }  @Override  public void run() {        try {            while(true) {        InetAddress inet = InetAddress.getByName(ip);                System.out.print(ip);        if( inet.isReachable(timeout) )          System.out.println("连接成功");        else          System.out.println("连接失败");      }    }    catch(IOException ex) {            ex.printStackTrace();    }  }}
  相关解决方案