最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java使用WatchService监控文件夹示例
时间:2022-06-29 01:42:22 编辑:袖梨 来源:一聚教程网
| 代码如下 | 复制代码 |
packageservice;
importconfig.Config; importjava.io.IOException; importjava.nio.file.*; importjava.util.List; importjava.util.concurrent.TimeUnit;
publicclassWatchDirService { privateWatchService watchService; privatebooleannotDone =true;
publicWatchDirService(String dirPath){ init(dirPath); }
privatevoidinit(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(); } }
publicvoidstart(){ System.out.print("watch..."); while(notDone){ try{ WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS);//此处将处于等待状态,等待检测到文件夹下得文件发生改变,返回WatchKey对象 if(watchKey !=null){ List for(WatchEvent event : events){ WatchEvent.Kind> kind = event.kind(); if(kind == StandardWatchEventKinds.OVERFLOW){ //当前磁盘不可用 continue; } WatchEvent Path path = 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("exit watch server"); break; } } }catch(InterruptedException e) { e.printStackTrace(); return; } } } } | |
就是这么简单就可以对一个文件夹进行监控了。
相关文章
- 魔兽世界怀旧服剧毒之水任务怎么处理-剧情梗概和任务条件 09-10
- 江湖悠悠开物台配方一览表-主要信息和内容重点 09-10
- 植物大战僵尸3冰晶赛季玩法有哪些重点-关键信息和实际影响 09-10
- tp886路由器怎么设置vl(tp886路由器设置vl方法) 09-10
- 植物大战僵尸3最后关打法有哪些重点-关键信息和实际影响 09-10
- tp886路由器桥接怎么设置(tp886路由器桥接设置方法) 09-10