Skip to content

Instantly share code, notes, and snippets.

@d6y
Created September 30, 2014 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d6y/85de2c7874af49cfc88c to your computer and use it in GitHub Desktop.
Save d6y/85de2c7874af49cfc88c to your computer and use it in GitHub Desktop.
Stream of File Watcher
import java.io._
import java.nio.file._
import scala.collection.JavaConversions._
object WatchStream {
// Watch service can watch multiple paths (as keys) but we're just using one
// so we can ws.take and assume whatever comes back is the path we care about.
private[this] val ws = FileSystems.getDefault.newWatchService()
private def events(key: WatchKey): Seq[WatchEvent[_]] = {
val es = key.pollEvents
key.reset()
es
}
// If you delete the path, the result is List(), but then NoSuchFileException during resolve
def apply(path: Path): Stream[Seq[Path]] = {
path.register(ws, StandardWatchEventKinds.ENTRY_CREATE)
Option(ws.take()).toSeq.flatMap(events).map(_.context).map{case p: Path => path.resolve(p)} #:: apply(path)
}
// What's the best way to stop reading?
// Would iteratee be better here?
// flatten to Stream[Path]? ... but may be a very large list of changes?
// seed with contents of path at start?
}
println("Doing")
val path = Paths.get("/tmp", "wdir")
WatchStream(path).foreach(p => println(p))
println("DONE")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment