Library contents

Groovy Path.register

Register and cancel a directory watch on a supported filesystem.

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

Groovy 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.groovy

Open 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.

First output linetrue
Lesson.groovy
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()
}
Output
true
false

The key is valid before cancellation and invalid afterwards.

Advertisements

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

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.

GivenCreate trip.txt
Worked resulttrip.txt

What to watch for

Handle overflow and rescan when a complete inventory is required.

Documentation for Path.register