java WatchService監控目錄變化

棗樹下的石磙發表於2020-11-28
 
public class Watcher {

    public static void main(String[] args) throws InterruptedException {
        try {
            WatchService watcher = FileSystems.getDefault().newWatchService();

            Paths.get("xxx").register(watcher,
                    new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_CREATE,
                            StandardWatchEventKinds.ENTRY_MODIFY,
                            StandardWatchEventKinds.ENTRY_DELETE},
                    SensitivityWatchEventModifier.HIGH);

            while (true) {
                //每隔3秒拉取監聽key
                WatchKey key = watcher.poll(3, TimeUnit.SECONDS);  //等待,超時就返回
                //監聽key為null,則跳過
                if (key == null) {
                    continue;
                }
                //獲取監聽事件
                for (WatchEvent<?> event : key.pollEvents()) {
                    //獲取監聽事件型別
                    WatchEvent.Kind<?> kind = event.kind();
                    Object context = event.context();
                    System.out.println(context);
                    String name = kind.name();
                    System.out.println(name);
                    do something......
                }
                //處理監聽key後(即處理監聽事件後),監聽key需要復位,便於下次監聽
                key.reset();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

 

相關文章