Created
September 30, 2014 07:53
-
-
Save d6y/85de2c7874af49cfc88c to your computer and use it in GitHub Desktop.
Stream of File Watcher
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._ | |
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