title: Java: Memory efficient ByteArrayOutputStream
body: <p>I've got a 40MB file in the disk and I need to "map" it into memory using a byte array.</p>
  
  <p>At first, I thought writing the file to a ByteArrayOutputStream would be the best way, but I find it takes about 160MB of heap space at some moment during the copy operation.</p>
  
  <p>Does somebody know a better way to do this without using three times the file size of RAM?</p>
  
  <p><strong>Update:</strong> Thanks for your answers. I noticed I could reduce memory consumption a little telling ByteArrayOutputStream initial size to be a bit greater than the original file size (using the exact size with my code forces reallocation, got to check why).</p>
  
  <p>There's another high memory spot: when I get byte[] back with ByteArrayOutputStream.toByteArray. Taking a look to its source code, I can see it is cloning the array:</p>
  
  <pre><code>public synchronized byte toByteArray()[] {
      return Arrays.copyOf(buf, count);
  }
  </code></pre>
  
  <p>I'm thinking I could just extend ByteArrayOutputStream and rewrite this method, so to return the original array directly. Is there any potential danger here, given the stream and the byte array won't be used more than once?</p>