Last active
December 22, 2015 10:29
-
-
Save ryoppy/6459294 to your computer and use it in GitHub Desktop.
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
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