Last active
August 29, 2015 14:21
-
-
Save Sciss/aa3c7f2f2f82ad8c4b49 to your computer and use it in GitHub Desktop.
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
| val fs = java.nio.file.FileSystems.getDefault | |
| val w = fs.newWatchService() | |
| val dir = userHome/"Documents"/"jack" | |
| val name = "fifo.log" | |
| val p = dir.toPath | |
| val wk = p.register(w, java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) | |
| new Thread { | |
| override def run(): Unit = { | |
| val f = dir / name | |
| var lastLen = f.length() | |
| while (true) { | |
| val wk2 = w.take() | |
| import scala.collection.JavaConversions._ | |
| val changed = wk2.pollEvents.exists { evt => | |
| // we only registered "ENTRY_MODIFY" so the context is always a Path. | |
| val p = evt.context.asInstanceOf[java.nio.file.Path] | |
| p.endsWith(name) | |
| } | |
| val valid = wk2.reset() | |
| if (!valid) { | |
| println("Key has been unregistered.") | |
| return | |
| } | |
| if (changed) { | |
| val newLen = f.length() | |
| val raf = new java.io.RandomAccessFile(f, "r") | |
| try { | |
| raf.seek(lastLen) | |
| val len = (newLen - lastLen).toInt | |
| val arr = new Array[Byte](len) | |
| raf.readFully(arr) | |
| val s = new String(arr, "UTF-8") | |
| println(":::: GOT ::::") | |
| println(s) | |
| } finally { | |
| raf.close() | |
| } | |
| lastLen = newLen | |
| } | |
| } | |
| } | |
| start() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment