Skip to content

Instantly share code, notes, and snippets.

@zentrope
Created July 1, 2011 03:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zentrope/1057824 to your computer and use it in GitHub Desktop.
Save zentrope/1057824 to your computer and use it in GitHub Desktop.
Scala InputStream for Memory Mapped File
// Just an example of some code I ended up not using, but which is kinda neat.
object Utils {
def linesFromFile(file: File) = {
io.Source.fromInputStream(getMemoryMappedFileInputStream(file)).getLines
}
def getMemoryMappedFileInputStream(file: File): InputStream = {
val channel: FileChannel = new FileInputStream(file).getChannel()
var buffer: ByteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size().toInt)
getMemoryMappedInputStream(buffer)
}
private def getMemoryMappedInputStream(buffer: ByteBuffer) =
new InputStream() {
override def read(): Int =
if (buffer.hasRemaining()) buffer.get else -1
override def read(bytes: Array[Byte], off: Int, len: Int): Int = {
if (buffer.hasRemaining()) {
val length = scala.math.min(len, buffer.remaining())
buffer.get(bytes, off, length)
length
} else {
-1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment