本篇文章给大家分享的是有关java项目中利用WatchService如何实现监控文件夹,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
通过java7提供的WatchService API 实现对文件夹的监控
package service;
import config.Config;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class WatchDirService {
private WatchService watchService;
private boolean notDone = true;
public WatchDirService(String dirPath){
init(dirPath);
}
private void init(String dirPath) {
Path path = Paths.get(dirPath);
try {
watchService = FileSystems.getDefault().newWatchService(); //创建watchService
path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE); //注册需要监控的事件,ENTRY_CREATE 文件创建,ENTRY_MODIFY 文件修改,ENTRY_MODIFY 文件删除
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
System.out.print("watch...");
while (notDone){
try {
WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS); //此处将处于等待状态,等待检测到文件夹下得文件发生改变,返回WatchKey对象
if(watchKey != null){
List<WatchEvent<?>> events = watchKey.pollEvents(); //获取所有得事件
for (WatchEvent event : events){
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW){
//当前磁盘不可用
continue;
}
WatchEvent<Path> ev = event;
Path path = ev.context();
if(kind == StandardWatchEventKinds.ENTRY_CREATE){
System.out.println("create " + path.getFileName());
}else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
System.out.println("modify " + path.getFileName());
}else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
System.out.println("delete " + path.getFileName());
}
}
if(!watchKey.reset()){
//已经关闭了进程
System.out.println("exit watch server");
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}
以上就是java项目中利用WatchService如何实现监控文件夹,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。