Suggesting a text change:
We read:
We’ve registered a WatchService to observe any change to the current directory.
but what actually happens is
We’ve registered a path with a filesystem
WatchService
to get told about ‘modification’ changes to the current directory.
On my system, file deletion does not give rise to a notification, but creation does (probably because after creation, the file is additionally modified)
The text
"Report any file changed within next 1 minute..."
should really say
System.out.println("Report the first change on '" + path + "' within the next 1 minute...");
Note that the code given uses an inner loop. At this point, I really feel we should use collect()
:
if(watchKey != null) {
watchKey.pollEvents()
.stream()
.forEach(event ->
System.out.println(event.context()));
}
Nicer:
String res = (watchKey == null) ? "nothing happened at all!" :
watchKey.pollEvents()
.stream()
.map(event -> event.context().toString())
.collect(Collectors.joining(", "));
As I had some trouble understanding how the WatchService actually works and what those keys are doing, here is the full method
public void watchFileChange() throws IOException {
final Path path = Paths.get(theDir);
String res;
// Try-with-resources to close the WatchService at the end
// (and thus cancel all the WatchKeys registered with it)
try (WatchService watchService = path.getFileSystem().newWatchService()) {
try {
// No need to retain the WatchKey returned by path.register()
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
System.out.println("Report the first change on '" + path + "' within the next 1 minute...");
WatchKey watchKey = null;
// poll() "Retrieves and removes the next watch key, waiting if necessary up to
// the specified wait time if none are yet present."
try {
watchKey = watchService.poll(1, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
System.out.println("Got interrupted");
}
res = (watchKey == null) ? "nothing happened at all!" :
watchKey.pollEvents()
.stream()
.map(event -> event.context().toString())
.collect(Collectors.joining(", "));
} catch (NoSuchFileException ex) {
res = "Looks like there is no filesystem entry '" + path + "'";
}
}
System.out.println(res);
}