经过实验后推测原因是idea每次rebuild会重新生成文件夹,
导致之前register失效。
解决方法在最后重新register
public static void main(String[] args) throws IOException, InterruptedException { WatchService watchService = FileSystems.getDefault().newWatchService(); Path path = Paths.get("D:\\project-2022\\java\\javaweb\\web\\WEB-INF\\classes\\com\\xpcf\\javaweb"); path.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); WatchKey key; while ((key = watchService.take()) != null) { for (WatchEvent<?> event : key.pollEvents()) { System.out.println( "Event kind:" + event.kind() + ". File affected: " + event.context() + "."); } key.reset(); // 使用后会增加一个数量级的时间在ns级别 path.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } }