Created
June 15, 2012 23:56
-
-
Save djangofan/2939268 to your computer and use it in GitHub Desktop.
Groovy script to watch a directory for changes in JDK1.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.IOException; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import java.nio.file.*; | |
// requires JDK 1.7.0+ | |
Path tmpPath = Paths.get( args[0]) | |
WatchService watchService = FileSystems.getDefault().newWatchService() | |
//Watching the /tmp/nio/ directory | |
//for MODIFY and DELETE operations | |
tmpPath.register( | |
watchService, | |
StandardWatchEventKinds.ENTRY_MODIFY, | |
StandardWatchEventKinds.ENTRY_DELETE); | |
for ( ; ; ) { | |
WatchKey key = watchService.take() | |
//Poll all the events queued for the key | |
for ( WatchEvent<?> event: key.pollEvents()){ | |
WatchEvent.Kind kind = event.kind() | |
switch (kind.name()){ | |
case "ENTRY_MODIFY": | |
System.out.println("Modified: "+event.context()) | |
break | |
case "ENTRY_DELETE": | |
System.out.println("Delete: "+event.context()) | |
break | |
} | |
} | |
//reset is invoked to put the key back to ready state | |
boolean valid = key.reset() | |
//If the key is invalid, just exit. | |
if ( !valid ) { | |
break | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment