gpt4 book ai didi

java - 将 Json 数组写入输出流时出现 OutOfMemoryError

转载 作者:行者123 更新时间:2023-12-02 13:42:34 25 4
gpt4 key购买 nike

我有 Java 程序,正在读取大小约为 40GB 的文件,并动态转换数据并流式传输到 DataOutputstream。

下面是我的代码

    JSONObject jsonObj= new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject properties = new JSONObject();

while((strLine = in.readLine()) != null)
{


if (jsonArray.length()%100 == 0) {

printJsonData(jsonArray);
// sendJsonData(jsonArray, output);
jsonArray = new JSONArray();
}

if (strLine.trim().contains("data")) {
jsonObj.put("properties",properties);
jsonArray.put(jsonObj);

if (strLine.trim().contains("data1")) {
String secondPart = strLine.split(":",2)[1];
properties.put("data1", secondPart);
continue;
}
if (strLine.trim().contains("id")) {
String secondPart = strLine.split(":",2)[1];
jsonObj.put("id", secondPart );
continue;

}

}

我有两种方法,一种是打印 JSON 数据,另一种是通过 https 发送 Json 数据。

private void printJsonData(JSONArray jsonArray) {
int count = jsonArray.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++){ // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject @ i position
System.out.println("jsonObject " + i + ": " + jsonObject);
}
}

private void sendJsonData(JSONObject jsonObj,DataOutputStream output) throws IOException {

int count = jsonArray.length();

for(int i=0 ; i< count; i++) { // iterate through jsonArray
JSONObject jsonObject = jsonArray.getJSONObject(i); // get jsonObject @ i position
System.out.println("Sending Data-->" + jsonObject.toString());
output.writeBytes(jsonObject.toString());
}
}

每当我调用打印方法时,一切都正常。但是当我调用 sendJsonData 方法时。我遇到内存不足错误。想知道如何修复它吗?

最佳答案

由于您没有以任何方式操作 json,所以我会将其视为文本文件并以这种方式发送。找到大 JsonObject 的可能性很大,因此您可能会付出太多努力。

除非有巨大的对象,否则 40GB 的数组是非常大的数组。

** 编辑 **

或者您可以将各个 json 对象视为"file"并单独推送这些字符串

关于java - 将 Json 数组写入输出流时出现 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42662098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com