使用WatchService监控文件变化

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/84478510
package com.nanhao.FileWatch;

import java.nio.file.*;

public class FileWatch {

    public static void main(String []args) throws Exception{
        WatchService watchService = FileSystems.getDefault().newWatchService();
        //为C盘根目录注册监听
        Paths.get("c:/").register(watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);
        while(true){
            WatchKey watchKey = watchService.take();
            for(WatchEvent<?>event : watchKey.pollEvents()){
                System.out.println(event.context()+"文件发生了"+event.kind()+"事件");
            }
            //重设WatchKey
            boolean valid = watchKey.reset();
            if(!valid){
                break;
            }
        }

    }

}

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/84478510