title: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at org.apache.commons.lang3.ArrayUtils
body: <p>I'm trying to read files from folders maximum of up to 3200~ files and storing them in the HashMap folder name is key and values are files inside the folder. Im getting <strong>java.lang.OutOfMemoryError: Java heap space</strong> Exception. Can anyone help? My JVM Heap size is _JAVA_OPTIONS: -Xms1024m -Xmx2048m. How to sort this out?</p>
  <pre><code>    private static final String FOLDER_PATH = &quot;H:\\NPA\\74RR\\Docs&quot;;
  
      public static Map&lt;String, Map&lt;Integer, Byte[]&gt;&gt; readFilesFromSystem() {
  
          File file = new File(FOLDER_PATH);
  
          
          // folders name example T74001, T74002, T74003
          String[] list = file.list();
  
          System.out.println(list.length);
          Map&lt;String, Map&lt;Integer, Byte[]&gt;&gt; map = new HashMap&lt;&gt;();
          // looping through single id documents
          for (String p : list) {
              Map&lt;Integer, Byte[]&gt; nestedMap = new HashMap&lt;Integer, Byte[]&gt;();
              File folder = new File(FOLDER_PATH + &quot;\\&quot; + p); // gives &quot;H:\\NPA\\Documents\\T74002
              File[] listOfFiles = folder.listFiles();
              for (int i = 0; i &lt; listOfFiles.length; i++) {
                  File xFiles = listOfFiles[i];
                  if (xFiles.isFile() &amp;&amp; xFiles.getName().toLowerCase().endsWith(&quot;.pdf&quot;)) {
                      try {
                          byte[] readFileToByteArray = FileUtils.readFileToByteArray(xFiles);
                          Integer docName = removeExtension(xFiles.getName());
                          long sizeInMb = readFileToByteArray.length / (1024 * 1024);
                          System.out.println(p + &quot;---File &quot; + docName + &quot; &quot; + sizeInMb + &quot;Mb&quot;);
                          Byte[] b = ArrayUtils.toObject(readFileToByteArray);
                          nestedMap.put(docName, b);
                      } catch (IOException e) {
                          e.printStackTrace();
                      } catch (InvalidFileFormatName e) {
                          e.printStackTrace();
                      }
                  }
              }
              map.put(p, nestedMap);
          }
          return map;
      }
  
      private static Integer removeExtension(String name) throws InvalidFileFormatName {
          try {
              name = name.substring(0, name.lastIndexOf(&quot;.&quot;));
          } catch (NumberFormatException e) {
              throw new InvalidFileFormatName(&quot;Invalid File Format &quot; + name);
          }
          return Integer.parseInt(name);
      }
  
      public static void main(String[] args) {
          readFilesFromSystem();
      }
  }
  
  </code></pre>