Since Java 1.7 you can use the Watch Service API to register for directory events. It is part of Java's New I/O (NIO) library and does not require any additional resources. An example how to use the API can be found in the official documentation.
After registering the WatchService you can retrieve events for the target path like this:
for (WatchEvent<?> event: key.pollEvents()) {
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s
", event.kind().name(), child);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…