title: Is there any way to handle Java heap space exception
body: <p>I am looking to convert file input stream for big file (The file is of 100MB) and it is throwing and java.lang.OutOfMemoryError : Java Heap space</p>
  
  <pre><code>import java.io.FileInputStream; import java.io.IOException;
  
  import org.apache.commons.io.IOUtils;
  
  public class TestClass {
      public static void main(String args[]) throws IOException
      {
          //Open the input and out files for the streams
          FileInputStream fileInputStream = new FileInputStream("file.pdf");
          IOUtils.toByteArray(fileInputStream);
      } 
  }
  </code></pre>
  
  <p>The actual stack trace is</p>
  
  <pre><code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
      at org.apache.commons.io.output.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:322)
      at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:463)
      at TestClass.main(TestClass.java:12)
  </code></pre>
  
  <p>I did tried to handle it using the below method </p>
  
  <pre><code>public static byte[] toByteArray(InputStream is) {
          if (is == null) {
              throw new NullPointerException("The InputStream parameter is null.");
          }
  
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          try {
              byte[] buffer = new byte[32];
              int read;
              while ((read = is.read(buffer)) != -1) {
                  baos.write(buffer, 0, read);
              }
              return baos.toByteArray();
          } catch (IOException e) {
  
          }
  </code></pre>
  
  <p>Which then fails with </p>
  
  <pre><code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
      at java.util.Arrays.copyOf(Arrays.java:2786)
      at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:94)
      at TestClass.toByteArray(TestClass.java:25)
      at TestClass.main(TestClass.java:14)
  </code></pre>
  
  <p>Is there any way we could handle this !!! Any inputs will be appreciated.</p>
  
  <p>Thanks !!!</p>