Library contents

Java Path.register

Subscribe a directory to file-system notifications using a WatchService.

A simple example

Path.register

  1. Start with A folder registered with a watcher
  2. Do this Cancel its watch key
  3. Result Key becomes invalid
Registration enables events for that folder. Cancelling the key stops that registration.

Syntax

Java syntax
WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException
JDK 21 declarations (2)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Watch an assignment inbox during office hours

A lab assistant wants to know when an assignment arrives. This setup registers a fresh inbox for creation events and cancels the subscription when the intake session ends.

First output linetrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            try (var watcher = desk.getFileSystem().newWatchService()) {
                var key = desk.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
                System.out.println(key.isValid());
                key.cancel();
                System.out.println(key.isValid());
            }
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
true
false

A valid key represents an active subscription. Cancellation ends it without depending on the timing of an incoming file.

Advertisements

Release a watcher when the desk closes

A receptionist starts a subscription for file deletions during check-in. Closing the service at the end of the shift should invalidate its active registration even when no event has arrived.

First output linetrue
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            var watcher = desk.getFileSystem().newWatchService();
            WatchKey key;
            try (watcher) {
                key = desk.register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
                System.out.println(key.isValid());
            }
            System.out.println(key.isValid());
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
true
false

Closing the service releases its resources and invalidates the key.

Detect a sheet music upload

A conductor watches a folder for newly uploaded parts. Register for new files before depositing the submission. Read the relative filename in the creation event.

GivenCreate alto.txt
Worked resultalto.txt
Code and output in Java
Java source
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path dir=Files.createTempDirectory("inbox-");
        try(var watcher=dir.getFileSystem().newWatchService()) {
            dir.register(watcher,StandardWatchEventKinds.ENTRY_CREATE);
            Files.createFile(dir.resolve("alto.txt"));
            var key=watcher.poll(8,TimeUnit.SECONDS);
            if (key == null) throw new IOException("No event received");
            System.out.println(key.pollEvents().get(0).context());
        } finally {
            Files.deleteIfExists(dir.resolve("alto.txt"));
            Files.delete(dir);
        }
    }
}
Output
alto.txt

What to watch for

Providers can combine events or report overflow. A consumer that needs a complete current inventory must handle that case by rescanning.

Documentation for Path.register