I'm getting a java.lang.OutOfMemoryError: Java heap space. I'm not sure what I'm doing wrong. Here is my code:
StringBuffer finalString = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader("collegeData 2.txt"));
StringBuffer returnFile = new StringBuffer();
returnFile.append(br.readLine() + br.readLine());
ArrayList<String> allData = new ArrayList<String>();
boolean completedFirstSection = false;
int count = 2;
String addString = "";
String nextLine;
while ((nextLine=br.readLine())!=null) {
if(count < 990) {
addString += nextLine;
count++;
} else {
String sub = nextLine.substring(16);
sub = sub.substring(0, sub.length());
addString = sub + ":{" + nextLine + "," + addString.substring(0, addString.length()-2) + br.readLine();
br.readLine();
allData.add(addString);
count = 2;
}
}
allData.add("}}]");
System.out.println("here");
System.out.println(returnFile.toString());
finalString = returnFile;
br.close();
} catch (IOException e) {
e.printStackTrace();
}
collegeData 2.txt is 44.2 mb and it is a json file. Here is my error message.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/jdk.internal.misc.Unsafe.allocateUninitializedArray(Unsafe.java:1250)
at java.base/java.lang.invoke.StringConcatFactory$MethodHandleInlineCopyStrategy.newArray(StringConcatFactory.java:1605)
at java.base/java.lang.invoke.DirectMethodHandle$Holder.invokeStatic(DirectMethodHandle$Holder)
at java.base/java.lang.invoke.LambdaForm$BMH/754666084.reinvoke(LambdaForm$BMH)
at java.base/java.lang.invoke.LambdaForm$MH/801197928.linkToTargetMethod(LambdaForm$MH)
at RunnerCombined.main(RunnerCombined.java:31)
RunnerCombined.java:31 is 'addString += nextLine' above.
Thank you in advance for your help!
StringBuilder, orStringBufferif synchronization is a concern, instead of aStringforaddString.Strings are immutable so every appending requires allocating a new object and copying.