title: Write a large Inputstream to File in Kotlin
body: <p>I have a large stream of text coming back from REST web service and I would like to write it directly to file. What is the simplest way of doing this?</p>
  
  <p>I have written the following function extension that WORKS. But I can't help thinking that there is a cleaner way of doing this.</p>
  
  <p><strong>Note</strong>: I was hoping to use try with resources to auto close the stream and file</p>
  
  <pre><code>fun File.copyInputStreamToFile(inputStream: InputStream) {
      val buffer = ByteArray(1024)
  
      inputStream.use { input -&gt;
          this.outputStream().use { fileOut -&gt;
  
              while (true) {
                  val length = input.read(buffer)
                  if (length &lt;= 0)
                      break
                  fileOut.write(buffer, 0, length)
              }
              fileOut.flush()
          }
      }
  }
  </code></pre>