java使用WatchService监控文件夹示例
通过java7提供的WatchServiceAPI实现对文件夹的监控
packageservice;
importconfig.Config;
importjava.io.IOException;
importjava.nio.file.*;
importjava.util.List;
importjava.util.concurrent.TimeUnit;
publicclassWatchDirService{
privateWatchServicewatchService;
privatebooleannotDone=true;
publicWatchDirService(StringdirPath){
init(dirPath);
}
privatevoidinit(StringdirPath){
Pathpath=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(IOExceptione){
e.printStackTrace();
}
}
publicvoidstart(){
System.out.print("watch...");
while(notDone){
try{
WatchKeywatchKey=watchService.poll(Config.POLL_TIME_OUT,TimeUnit.SECONDS);//此处将处于等待状态,等待检测到文件夹下得文件发生改变,返回WatchKey对象
if(watchKey!=null){
List<WatchEvent<?>>events=watchKey.pollEvents();//获取所有得事件
for(WatchEventevent:events){
WatchEvent.Kind<?>kind=event.kind();
if(kind==StandardWatchEventKinds.OVERFLOW){
//当前磁盘不可用
continue;
}
WatchEvent<Path>ev=event;
Pathpath=ev.context();
if(kind==StandardWatchEventKinds.ENTRY_CREATE){
System.out.println("create"+path.getFileName());
}elseif(kind==StandardWatchEventKinds.ENTRY_MODIFY){
System.out.println("modify"+path.getFileName());
}elseif(kind==StandardWatchEventKinds.ENTRY_DELETE){
System.out.println("delete"+path.getFileName());
}
}
if(!watchKey.reset()){
//已经关闭了进程
System.out.println("exitwatchserver");
break;
}
}
}catch(InterruptedExceptione){
e.printStackTrace();
return;
}
}
}
}
就是这么简单就可以对一个文件夹进行监控了。
完整带码地址:WatchServerDemo_jb51.rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。