踢脚线安装,天庭剩女,诺诺芷琪
通过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; } } } }
就是这么简单就可以对一个文件夹进行监控了。
完整带码地址:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论