import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.concurrent.TimeUnit; public class FileLiting { public static void main(String[] args) throws IOException, InterruptedException { //获取监听路径 String url = Thread.currentThread().getContextClassLoader().getResource("").getPath(); url = url.substring(1, url.length()-1); WatchService watchService = FileSystems.getDefault().newWatchService(); //注册文件监听 Paths.get(url).register(watchService, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY }); while(true) { //三秒拉取 WatchKey watchKey = watchService.poll(3, TimeUnit.SECONDS); if(watchKey==null) { System.out.println("没有变化"); continue; } for(WatchEvent<?> event:watchKey.pollEvents()) { System.out.println("文件名:"+event.context().toString()); if(event.kind()==StandardWatchEventKinds.ENTRY_MODIFY) { System.out.println("文件修改"); } if(event.kind()==StandardWatchEventKinds.ENTRY_DELETE) { System.out.println("文件删除"); } } //监听复位 watchKey.reset(); } } }
JAVA对文件实现监听
原文:https://www.cnblogs.com/sthh/p/12966396.html