Java Path.register
Subscribe a directory to file-system notifications using a WatchService.
A simple example
Path.register
- Start with A folder registered with a watcher
- Do this Cancel its watch key
- Result Key becomes invalid
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.javaWatch 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.
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);
}
}
}
}
true false
A valid key represents an active subscription. Cancellation ends it without depending on the timing of an incoming file.
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.
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);
}
}
}
}
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.
Code and output in Java
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);
}
}
}
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.