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.
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
}