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 java.lang.OutOfMemoryError: Java heap space Exception. Can anyone help? My JVM Heap size is _JAVA_OPTIONS: -Xms1024m -Xmx2048m. How to sort this out?
private static final String FOLDER_PATH = "H:\\NPA\\74RR\\Docs";
public static Map<String, Map<Integer, Byte[]>> readFilesFromSystem() {
File file = new File(FOLDER_PATH);
// folders name example T74001, T74002, T74003
String[] list = file.list();
System.out.println(list.length);
Map<String, Map<Integer, Byte[]>> map = new HashMap<>();
// looping through single id documents
for (String p : list) {
Map<Integer, Byte[]> nestedMap = new HashMap<Integer, Byte[]>();
File folder = new File(FOLDER_PATH + "\\" + p); // gives "H:\\NPA\\Documents\\T74002
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File xFiles = listOfFiles[i];
if (xFiles.isFile() && xFiles.getName().toLowerCase().endsWith(".pdf")) {
try {
byte[] readFileToByteArray = FileUtils.readFileToByteArray(xFiles);
Integer docName = removeExtension(xFiles.getName());
long sizeInMb = readFileToByteArray.length / (1024 * 1024);
System.out.println(p + "---File " + docName + " " + sizeInMb + "Mb");
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("."));
} catch (NumberFormatException e) {
throw new InvalidFileFormatName("Invalid File Format " + name);
}
return Integer.parseInt(name);
}
public static void main(String[] args) {
readFilesFromSystem();
}
}