java使用WatchService监控文件夹示例
程序员文章站
2024-03-06 15:38:02
通过java7提供的watchservice api 实现对文件夹的监控
package service;
import config.config;
i...
通过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; } } } }
就是这么简单就可以对一个文件夹进行监控了。
完整带码地址:watchserverdemo_jb51.rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。