title: How to write the contents of a Scala stream to a file?
body: <p>I have a Scala stream of bytes that I'd like to write to a file.  The stream has too much data to buffer all of it memory.</p>
  
  <p>As a first attempt, I created an <code>InputStream</code> similar to this:</p>
  
  <pre><code>class MyInputStream(data: Stream[Byte]) extends InputStream {
    private val iterator = data.iterator
    override def read(): Int = if (iterator.hasNext) iterator.next else -1
  }
  </code></pre>
  
  <p>Then I use Apache Commons to write the file:</p>
  
  <pre><code>val source = new MyInputStream(dataStream)
  val target = new FileOutputStream(file)
  try {
    IOUtils.copy(source, target)
  } finally {
    target.close
  }
  </code></pre>
  
  <p>This works, but I'm not too happy with the performance.  I'm guessing that calling <code>MyInputStream.read</code> for every byte introduces a lot of overhead.  Is there a better way?</p>