简体   繁体   English

写入文件时出现Java堆空间错误

[英]java heap space error while writing to a file

I am trying to write a huge data around 64000 records at a time to a file. 我正在尝试一次将大约64000条记录的巨大数据写入一个文件。 I am getting exceptions that I attached bellow. 我正在附上下面的例外。 在此处输入图片说明

the code that I used to write is 我以前写的代码是

Path outputpath = Paths.get("file1.json");
try (BufferedWriter writer = Files.newBufferedWriter(outputpath, StandardCharsets.UTF_8, WRITE)) {
 writer.write(jsonObject.toString());
} catch (Exception e) {
//error msg
}

Here my "jsonObject" is nothing but a json Array which contains 65000 rows . 在这里,我的“ jsonObject”不过是一个包含65000行的json数组。

Can you please help me to write this to my file in an efficient way ,so that I can avoid that heap Space Error . 能否请您帮我一种有效的方式将此文件写入我的文件,以免发生堆空间错误

You've cut your stacktrace a little bit short, but I'll assume the exception happens in jsonObject.toString(). 您已经将stacktrace缩短了一些,但是我假设该异常发生在jsonObject.toString()中。

Basically, you have to decide between two things: either allocate more memory or break the big operation into several smaller ones. 基本上,您必须在两件事之间做出选择:分配更多的内存或将大型操作分解为几个较小的操作。 Adding memory is quick and simple, but if you expect even more data in the future, it won't solve your problem forever. 添加内存既快速又简单,但是如果将来您希望获得更多数据,它将永远无法解决您的问题。 As others have mentioned, use -Xmx and/or -Xms on java command line. 正如其他人提到的,在Java命令行上使用-Xmx和/或-Xms。

The next thing you could try is to use a different JSON library. 您可以尝试的下一件事是使用其他JSON库。 Perhaps the one you are using now is not particularly suited for large JSON objects. 也许您现在使用的那个并不特别适合大型JSON对象。 Or there might be a newer version. 或者可能有较新的版本。

As the last resort, you can always construct the JSON yourself. 作为最后的手段,您始终可以自己构造JSON。 It's a string after all, and you already have the data in memory. 毕竟这是一个字符串,您已经在内存中存储了数据。 To be as efficient as possible, you don't even need to build the entire string at once, you could just go along and write bits and pieces to your BufferedWriter. 为了尽可能地提高效率,您甚至不需要一次构建整个字符串,您可以继续将零零碎碎地写入BufferedWriter。

You can try to iterate through your json object: 您可以尝试遍历 json对象:

Iterator<String> keys = (Iterator<String>) jsonObject.keys();
while (keys.hasNext()) {
    String key = keys.next();
    JSONObject value = jsonObject.getJSONObject(key);
    writer.write(value.toString());
}

PS. PS。 You need to check your json object's structure. 您需要检查json对象的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM