1

I get this error: "OutOfMemoryError: Java heap space", when save a big jsonObject on file with FileWriter

My code:

FileWriter  file2 = new FileWriter("C:\\Users\\....\\test.json");
file2.write(jsonObject.toString());
file2.close();

My pom

<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>

Would greatly appreciate your help and thanks in advance.

alessio1985
  • 503
  • 1
  • 5
  • 14

2 Answers2

3

By using toString() you're creating a string object first, before writing it to the FileWriter, which consumes a lot of memory for large objects. You should use JSONObject.writeJSONString(Writer) to reduce the memory footprint:

final JSONObject obj = ...
    
try (final Writer writer = new FileWriter(new File("output"))) {
    obj.writeJSONString(writer);
}
catch (IOException e) {
    // handle exception
}
majusebetter
  • 1,458
  • 1
  • 4
  • 13
0

Maybe this answer helps you to solve your issue. It could be possible that your JVM does not have enough (free) memory. Another solution could be to split a large JSON object into many smaller ones.

NicoHahn
  • 23
  • 5