Skip to content

Instantly share code, notes, and snippets.

@takezoe
Created November 17, 2011 06:21
Show Gist options
  • Save takezoe/1372510 to your computer and use it in GitHub Desktop.
Save takezoe/1372510 to your computer and use it in GitHub Desktop.
wraps java.io.InputStream by scala.collection.immutable.Stream
val stream = fromInputStream(new java.io.FileInputStream("test.jpg"), 8 * 1024)
/**
* Makes Stream which reads every bytes with specified size from java.io.InputStream.
*/
@tailrec
def fromInputStream(in: java.io.InputStream, bufferSize: Int): Stream[Array[Byte]] = {
val buffer = new Array[Byte](bufferSize)
in.read(buffer) match {
case -1 => Stream.empty
case len => buffer.slice(0, len) #:: fromInputStream(in, bufferSize)
}
}
@xuwei-k
Copy link

xuwei-k commented Nov 17, 2011

これ

def fromInputStream(s:java.io.InputStream) = 
  Iterator.continually(s.read).takeWhile(-1 !=).map{_.toByte} // 場合によっては Stream.continually ?

より、ある一定サイズの Array[Byte] に読み込んだほうが効率いいんですかね?

InputStream の内部実装によるかな・・・

@takezoe
Copy link
Author

takezoe commented Nov 17, 2011

直接FileInputStreamとか読むならある程度のサイズをまとめて読んだほうが圧倒的に速いです。
BufferedInputStreamかましたときは…どうなんでしょう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment