-
-
Save sjvkishore/25baca60f7ab77a59eed4d1554be216d to your computer and use it in GitHub Desktop.
Scala InputStream for Memory Mapped File
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
// 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