Java如何监视文件或目录的更改?
package org.nhooo.example.io; import java.io.IOException; import java.nio.file.*; import static java.nio.file.StandardWatchEventKinds.*; public class FileWatchDemo { public static void main(String[] args) { try { //创建WatchService的实例。 WatchService watcher = FileSystems.getDefault().newWatchService(); //在下面的监视服务中注册logDir。 Path logDir = Paths.get("/Users/nhooo/temp/"); logDir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE); //在侦听更改通知时监视logDir。 while (true) { WatchKey key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (ENTRY_CREATE.equals(kind)) { System.out.println("Entry was created on log dir."); } else if (ENTRY_MODIFY.equals(kind)) { System.out.println("Entry was modified on log dir."); } else if (ENTRY_DELETE.equals(kind)) { System.out.println("Entry was deleted from log dir."); } } key.reset(); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
要获取创建,修改或删除的文件,您可以看到以下示例:使用WatchService时如何获取文件名?