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.

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.