Groovy Path.register
Register and cancel a directory watch on a supported filesystem.
A simple example
Path.register
- Start with A folder registered with a watcher
- Do this Cancel its watch key
- Result Key becomes invalid
Syntax
base.register(watcher, eventKind)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyOpen and close an assignment subscription
A tutor collects submissions during office hours. Register a temporary directory for new-file notifications and cancel the registration when collection ends so the application can release the watcher.
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
Path base = Files.createTempDirectory("lesson-")
try {
base.fileSystem.newWatchService().withCloseable { watcher ->
def key = base.register(watcher, StandardWatchEventKinds.ENTRY_CREATE)
println key.valid
key.cancel()
println key.valid
}
} finally {
base.toFile().deleteDir()
}
true false
The key is valid before cancellation and invalid afterwards.
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.
Detect a field-trip form
A school clerk watches the permissions inbox during registration. Register for new files before depositing the submission. Read the relative filename in the creation event.
What to watch for
Handle overflow and rescan when a complete inventory is required.