Skip to content

Instantly share code, notes, and snippets.

@guersam
Last active June 15, 2016 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guersam/fd0348d51888f6eeb429500dd134532b to your computer and use it in GitHub Desktop.
Save guersam/fd0348d51888f6eeb429500dd134532b to your computer and use it in GitHub Desktop.
Java nio live file reader in akka stream
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