Java WatchService API Tutorial


In this example, we will learn to watch a directory along with all sub-directories and files inside it, using java 8 WatchService API.

How to register Java 8 WatchService

To Register WatchService, get the directory path and use path.register() method.


Path path = Paths.get(".");
WatchService watchService =  path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

Watching for change events

To get the changes occured on directory and files inside it, use watchKey.pollEvents() method which return the collection of all change events in form of stream.

WatchKey watchKey = null;
while (true) {
    watchKey = watchService.poll(10, TimeUnit.MINUTES);
    if(watchKey != null) {
        watchKey.pollEvents().stream().forEach(event -> System.out.println(event.context()));
    }
    watchKey.reset();
}

The key remains valid until:

  • It is cancelled, explicitly, by invoking its cancel method, or
  • Cancelled implicitly, because the object is no longer accessible, or
  • By closing the watch service.
  • Watch Directory, Sub-directories and Files for Changes Example

    In this example, we will see an example of watching a directory with all sub-directories and files inside it. We will maintain a map of watch keys and directories Map<WatchKey, Path> keys to correctly identify which directory has been modified.

    Below method will register a single directory to watcher and then store the directory and key inside a map.

    private void registerDirectory(Path dir) throws IOException
    {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        keys.put(key, dir);
    }
    We will call this method recursively while walking down a directory structure and calling this for each directory we encounter.
    private void walkAndRegisterDirectories(final Path start) throws IOException {
        // register directory and sub-directories
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                registerDirectory(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition