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;
}
}
}
}