fedor.belov fedor.belov - 1 year ago 96
Java Question

Can I watch for single file change with WatchService (not the whole directory)?

When I'm trying to register a file instead of a directory

is thrown. Can I listen for a single file change, not the whole directory?

Answer Source

Just filter the events for the file you want in the directory:

final Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop");
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
    final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
    while (true) {
        final WatchKey wk = watchService.take();
        for (WatchEvent<?> event : wk.pollEvents()) {
            //we only register "ENTRY_MODIFY" so the context is always a Path.
            final Path changed = (Path) event.context();
            if (changed.endsWith("myFile.txt")) {
                System.out.println("My file has changed");
        // reset the key
        boolean valid = wk.reset();
        if (!valid) {
            System.out.println("Key has been unregisterede");

Here we check whether the changed file is "myFile.txt", if it is then do whatever.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download