I have the following code for reading a file of about 300MB of size and the execution is interrumped by a "java.lang.OutOfMemoryError: Java heap space" exception:
import java.io.*;
import java.util.*;
class MainClass {
static ArrayList<String> getAttribute(String str) {
if(str==null) return null;
ArrayList<String> a = new ArrayList<>();
int i = 0;
int j = -1;
while(i<str.length() && j<str.length()) {
j = str.indexOf(',',i);
if(j==-1) j = str.length();
a.add(str.substring(i,j));
i = str.indexOf(',',j)+1;
}
return a;
}
static ArrayList<ArrayList<String>> readFile(String in) throws IOException {
ArrayList<ArrayList<String>> a = new ArrayList<>();
try(FileInputStream fin = new FileInputStream(in);) {
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
String str = br.readLine();
while(str!=null) {
a.add(getAttribute(str));
str = br.readLine(); //line 26
}
}
return a;
}
public static void main(String args[]) throws IOException
{
readFile("stats1.csv"); //line 34
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at MainClass.readFile(MainClass.java:26)
at MainClass.main(MainClass.java:34)
What is the cause of this error? or is it just that the file is too big?