Watch directory for modification in Java
Description
The following code shows how to watch directory for modification.
Example
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
/*ww w. java 2 s. com*/
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Main {
public static void main(String[] args) throws Exception {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = FileSystems.getDefault().getPath("c:/");
WatchKey key = dir.register(watcher, ENTRY_MODIFY);
while (true) {
key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_MODIFY) {
System.out.println("Home dir changed!");
}
}
key.reset();
}
}
}