我想一直去连一个IP,也就是PING那个IP地址,求帮忙写个程序一直PINT它,如果连同就打印连接成功,否则打印连接失败。
解决方案 »
- BufferedReader乱码问题,在线抢分咯~
- java反射中的一个问题,高手帮我看看
- 在往分了区的表中添加记录时总是提示“这类索引的分区处于不可用状态”
- 有个数据传输的问题困扰小弟很久,今天贴出来,请各位达人指点。
- JCreator下编写,怎么样把参考传进去,这样编译运行时能显示出传递的参数呢???
- hibernate级联更新如何配置:自引用(本表外键即本表主键)
- 哪个java报表可以打印条码,有人实现吗?高分相赠!
- 谁知道字符串替换的类的方法呀?
- 我要急死了!!这里竟然没人能给我一个满意的答案!!????
- JAVA里如何进行类型转换?
- 用map保存一个相同key里的数据
- smartupload 上传路径问题 请高手回答
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"));
}
}
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();
}
}
}