使用WatchService监视主用户目录上文件的创建,删除或修改
import java.nio.file.*; import java.util.Properties; /* N o w J a v a . c o m - 时代Java 提供 */ public class WatchServiceExample { public static void main(String[] args) throws Exception { FileSystem fs = FileSystems.getDefault(); WatchService ws = fs.newWatchService(); Properties props = System.getProperties(); String homePath = props.get("user.home").toString(); Path home = fs.getPath(homePath); home.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW); /* from 时 代 Java 公 众 号 - nowjava.com*/ System.out.println("Monitoring file creation in " + home + "... (Ctrl+C to quit)"); while (true) { WatchKey key = ws.take(); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { Path item = (Path)event.context(); System.out.println("Created: " + item); } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) { Path item = (Path)event.context(); System.out.println("Removed: " + item); } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { Path item = (Path)event.c