WatchService类的使用

WatchService是java的NIO类新增加的监控文件变化的类。

WatchService是一个接口,利用Filesystems类获取FileSystem,然后根据这个类,new一个WatchService。
具体用法如下
 public static void main(String[] args) throws Exception {
        //WatchService是一个接口,利用Filesystems类获取FileSystem,然后根据这个类,new一个WatchService。
        WatchService watchService= FileSystems.getDefault().newWatchService();
        Paths.get("G:/").register(watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);
        while (true){
            WatchKey key=watchService.take();
            for(WatchEvent<?>evet:key.pollEvents()){
                System.out.println(evet.context()+"文件发生了"+evet.kind()+"事件");
            }
            boolean vaild=key.reset();
            if(!vaild){
                break;
            }
        }
    }

  

 注意当重命名一个文件夹或者文件时,他会显示先删除再创建。

注意,例子中的take方法时阻塞的方法。

还有poll,如果获取不到watchkey,立马返回null,还有一个poll(long timeout,timeuint unit)设定一个等待时间。

猜你喜欢

转载自www.cnblogs.com/tomato190/p/12668637.html