10年 Java程序员,硬核人生!勇往直前,永不退缩!

欢迎围观我的git:https://github.com/R1310328554/spring_security_learn 寻找志同道合的有志于研究技术的朋友,关注本人微信公众号: 觉醒的码农,或Q群 165874185

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

原来可以这样用java来监控文件,

 

private static void nio() throws IOException {
WatchService watcher = null;
try {
try {
watcher = FileSystems.getDefault().newWatchService();
String path = "D:\\test\\as";// 要监控的文件或者目录
Paths.get(path).register(watcher,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

while (true) {
WatchKey key = null;
try {
key = watcher.take();
} catch (InterruptedException e) {
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {

WatchEvent.Kind<?> kind = event.kind();

if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_MODIFY
|| kind == StandardWatchEventKinds.ENTRY_CREATE
|| kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("AAAAAAAASSS");// 处理特定事件!
break;
}
}
key.reset();

}
}

 

posted on 2014-02-15 10:09  CanntBelieve  阅读(181)  评论(0编辑  收藏  举报