Path path = Paths.get("path"); if (Files.exists(path)) { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE ); while (true) { WatchKey key = watchService.take(); // 阻塞 for (WatchEvent<?> event : key.pollEvents()) { WatchEvent <Path> EV = (WatchEvent <Path>) Event; Path File = ev.context (); // get the event documents
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) { // 创建时 }
if (StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { // 修改时 }
IF (StandardWatchEventKinds.ENTRY_DELETE.equals (event.kind ())) { // When delete } } key.reset (); Clear the queue key // After successful treatment, or follow-up event can not be triggered } } the catch (IOException | E InterruptedException) { e.printStackTrace (); }
Few notes
Registration does not support monitoring of a single document, if pathnot 文档夹thrownjava.nio.file.NotDirectoryException