Skip to content

Instantly share code, notes, and snippets.

@ryoppy
Last active December 22, 2015 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryoppy/6459294 to your computer and use it in GitHub Desktop.
Save ryoppy/6459294 to your computer and use it in GitHub Desktop.
Scalaでファイル変更監視
import java.nio.file.{ FileSystem, FileSystems, WatchKey, WatchService, StandardWatchEventKinds }
import java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY
import scala.collection.JavaConverters._
import scala.concurrent._
import ExecutionContext.Implicits.global
object Main {
def main(args: Array[String]) {
FileWatcher("/tmp/build/classes", "hoge.html").watch {
println("change")
}
// 何かの処理中に、ファイルに変更があるとfireされる
Thread.sleep(100000)
}
}
/**
* 指定したファイルを監視
* @param dir 監視したいディレクトリ
* @param file 監視したいファイル
*/
case class FileWatcher(dir: String, file: String) {
/**
* 監視を開始
* @param callback
*/
def watch(callback: => Unit): Unit = future {
val fs: FileSystem = FileSystems.getDefault()
val ws: WatchService = fs.newWatchService()
fs.getPath(dir).register(ws, ENTRY_MODIFY)
Option(ws.take) match {
case Some(key) => {
if (key.pollEvents.asScala.exists((e) => (e.kind == ENTRY_MODIFY && e.context.toString == file))) callback
}
case None =>
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment