Skip to content

Instantly share code, notes, and snippets.

@der3k
Last active December 2, 2016 13:56
Show Gist options
  • Save der3k/edb0c416262742ee75b728b8b3d811ac to your computer and use it in GitHub Desktop.
Save der3k/edb0c416262742ee75b728b8b3d811ac to your computer and use it in GitHub Desktop.
Java NIO2 watch service example
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchKey
import java.nio.file.WatchService
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY
def watchService = FileSystems.getDefault().newWatchService()
def path = Paths.get(System.getProperty('user.home'), "/watching")
println path
path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY)
WatchKey key
while ((key = watchService.take()) != null) {
key.pollEvents().each { event ->
println "event ${event.kind()} on '${event.context()}'"
}
key.reset()
}
watchService.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment