alessio1985
alessio1985

Reputation: 513

Java heap space error when save json file

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.

Upvotes: 1

Views: 1197

Answers (2)

majusebetter
majusebetter

Reputation: 1592

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
}

Upvotes: 3

NicoHahn
NicoHahn

Reputation: 48

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.

Upvotes: 0

Related Questions