Last active
June 15, 2016 15:02
-
-
Save guersam/fd0348d51888f6eeb429500dd134532b to your computer and use it in GitHub Desktop.
Java nio live file reader in akka stream
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 akka.streams.scaladsl._ | |
import akka.util.ByteString | |
import java.nio.ByteBuffer | |
import java.nio.file.Path | |
import java.nio.channels.FileChannel | |
def logFileReader(path: Path, bufferSize: Int = 4096) | |
Source.unfoldResource[ByteString, (ByteBuffer, FileChannel)]( | |
() => (ByteBuffer.allocateDirect(bufferSize), FileChannel.open(path, StandardOpenOption.READ)), | |
{ | |
case (buf, chan) => | |
// ignore -1 (EOF) to watch the end | |
val chunk = | |
if (chan.read(buf) > 0) { | |
buf.flip() | |
val bs = ByteString(buf) | |
buf.clear() | |
bs | |
} else ByteString.empty | |
Some(chunk) | |
}, | |
{ case (_, chan) => chan.close() } | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment