I have a Scala byte stream that I would like to write to a file. There is too much data in the stream to buffer all of its memory.
As a first attempt, I created InputStreamone similar to this:
class MyInputStream(data: Stream[Byte]) extends InputStream {
private val iterator = data.iterator
override def read(): Int = if (iterator.hasNext) iterator.next else -1
}
Then I use Apache Commons to write the file:
val source = new MyInputStream(dataStream)
val target = new FileOutputStream(file)
try {
IOUtils.copy(source, target)
} finally {
target.close
}
It works, but I'm not too happy with the performance. I assume that calling MyInputStream.readfor each byte introduces a lot of overhead. Is there a better way?
source
share