-
-
Save saswata-dutta/a033393714f5ec9dddf44084c7a29d1c to your computer and use it in GitHub Desktop.
Read a file using Stream (Scala)
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
import java.io.File | |
import java.io.FileInputStream | |
case class Chunk(length: Int, bytes: Array[Byte]) | |
def fileContentStream(fileIn: FileInputStream): Stream[Chunk] = { | |
val bytes = Array.fill[Byte](1024)(0) | |
val length = fileIn.read(bytes) | |
Chunk(length, bytes) #:: fileContentStream(fileIn) | |
} | |
def usingFileInput[T](filename: String)(f: (Stream[Chunk]) => T): T = { | |
val fileInputStream = new FileInputStream(new File(filename)) | |
val stream = fileContentStream(fileInputStream) takeWhile { chunk => chunk.length > 0 } | |
val result = f(stream) | |
fileInputStream.close() | |
result | |
} | |
val file = new File("/Users/mumoshu/Pictures/512.png") | |
val fileIn = new FileInputStream(file) | |
in(fileIn) filter { chunk => chunk._2 > 0 } foreach { chunk => chunk._2 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment