Created
September 25, 2011 22:45
-
-
Save eberle1080/1241276 to your computer and use it in GitHub Desktop.
Uses the Java 7 WatchEvent filesystem API from within Scala
This file contains hidden or 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
/** | |
* watcher.scala | |
* | |
* Uses the Java 7 WatchEvent filesystem API from within Scala. | |
* Based on http://markusjais.com/file-system-events-with-java-7/ | |
* | |
* @author Chris Eberle <[email protected]> | |
* @version 0.1 | |
*/ | |
import scala.collection.JavaConverters._ | |
import util.control.Breaks._ | |
import java.io.IOException | |
import java.nio.file.Path | |
import java.nio.file.StandardWatchEventKinds | |
import java.nio.file.WatchEvent | |
import java.nio.file.WatchKey | |
import java.nio.file.WatchService | |
import java.nio.file.FileSystems | |
class DirectoryWatcher(val path:Path) extends Runnable { | |
def printEvent(event:WatchEvent[_]) : Unit = { | |
val kind = event.kind | |
val event_path = event.context().asInstanceOf[Path] | |
if(kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) { | |
println("Entry created: " + event_path) | |
} | |
else if(kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) { | |
println("Entry deleted: " + event_path) | |
} | |
else if(kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) { | |
println("Entry modified: " + event_path) | |
} | |
} | |
override def run(): Unit = { | |
try { | |
val watchService = path.getFileSystem().newWatchService() | |
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, | |
StandardWatchEventKinds.ENTRY_MODIFY, | |
StandardWatchEventKinds.ENTRY_DELETE) | |
breakable { | |
while (true) { | |
val watchKey = watchService.take() | |
watchKey.pollEvents().asScala.foreach( e => { | |
printEvent(e) | |
}) | |
if (!watchKey.reset()) { | |
println("No longer valid") | |
watchKey.cancel() | |
watchService.close() | |
break | |
} | |
} | |
} | |
} catch { | |
case ie: InterruptedException => println("InterruptedException: " + ie) | |
case ioe: IOException => println("IOException: " + ioe) | |
case e: Exception => println("Exception: " + e) | |
} | |
} | |
} | |
println("Starting watch service...") | |
val path = FileSystems.getDefault().getPath("/home/chris/scala/watch") | |
val dir_watcher = new DirectoryWatcher(path) | |
val watch_thread = new Thread(dir_watcher) | |
watch_thread.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment