Code: Select all
Given the following code for monitoring a directory:
Path path = Paths.get(".");
WatchService watchService = FileSystems.getDefault().newWatchService();
path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while(true) {
WatchKey key = watchService.take();
System.out.println(key.isValid());
for (WatchEvent<?> watchEvent : key.pollEvents()) {
Kind<?> kind = watchEvent.kind();
System.out.println(kind);
}
}
A file is created and then deleted from the monitored directory. How many events will be printed by the above code?
In practice, certainly on my machine at least (Ubuntu), when a new file is created I get both an ENTRY_CREATE and an ENTRY_MODIFY. This may differ on Windows and I suspect the events you receive would be platform dependent as file operations will behave differently.Once you retrieve a key from WatchService, you can't get further events until you call key.reset().
In this case, the code will get the create event but since it does not call reset() on the key before repeating the loop, it will not receive the delete event.
Am I right or have I missed something?
Thanks for reading and for any help you may be able to provide.