Java WatchService API Tutorial
In this precedent, we will figure out how to watch an index alongside all sub-registries and records inside it, utilizing java 8 WatchService API.
How to enroll Java 8 WatchService
To Register WatchService, get the registry way and use path.register() method.
Path way = Paths.get(
WatchService watchService = path.getFileSystem().newWatchService();
Watching for change events
To get the progressions occured on registry and documents inside it, use watchKey.pollEvents() technique which return the accumulation of all change occasions in type of stream.
WatchKey watchKey =
watchKey = watchService.poll(
watchKey.pollEvents().stream().forEach(event - > System.out.println(event.context()));
The key stays legitimate until:
- It is dropped, expressly, by conjuring its drop technique, or
- Cancelled certainly, in light of the fact that the item is never again available, or
- By shutting the watch service.
Watch Directory, Sub-registries and Files for Changes Example
In this model, we will see a case of viewing a catalog with all sub-registries and documents inside it. We will keep up a guide of watch keys and registries
Map<WatchKey, Path> keys to effectively distinguish which index has been modified.
Below strategy will enroll a solitary catalog to watcher and after that store the registry and key inside a map.
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
//register registry and sub-directories
FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)