title: How to write a potentially huge InputStream to File?
body: <p>I have an API call that returns a byte array. I currently stream the result into a byte array then make sure the checksums match and then write the ByteArrayOutputStream to File.  The code is something like this and it works pretty well. </p>
  
  <pre><code>    String path = "file.txt";
      ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
      int bufferSize = 1024;
      byte[] buffer = new byte[bufferSize];
      int len = 0;
      while ((len = inputStream.read(buffer)) != -1) {
          byteBuffer.write(buffer, 0, len);
      }
      FileOutputStream stream = new FileOutputStream(path); 
      stream.write(byteBuffer.toByteArray());
  </code></pre>
  
  <p>My concern i that the result from inputstream could potentially be larger than the heap size in android and I could get OutOfMemory exceptions if the entire byte array is in memory. What is the most elegant way to write the inputStream to file in chunks, such that the byte array is never larger than the heap size?</p>