gpt4 book ai didi

java - 谷歌数据流 : how to parse big file with valid JSON array from FileIO. 可读文件

转载 作者:太空宇宙 更新时间:2023-11-04 10:44:01 24 4
gpt4 key购买 nike


在我的管道中,FileIO.readMatches() 转换使用有效的 JSON 数组读取大型 JSON 文件(大约 300-400MB),并将 FileIO.ReadableFile 对象返回到下一个转换。我的任务是从该 JSON 数组中读取每个 JSON 对象,添加新属性并输出到下一个转换。

目前我解析 JSON 文件的代码如下所示:

        // file is a FileIO.ReadableFile object 
InputStream bis = new ByteArrayInputStream(file.readFullyAsBytes());
// Im using gson library to parse JSON
JsonReader reader = new JsonReader(new InputStreamReader(bis, "UTF-8"));
JsonParser jsonParser = new JsonParser();
reader.beginArray();
while (reader.hasNext()) {
JsonObject jsonObject = jsonParser.parse(reader).getAsJsonObject();
jsonObject.addProperty("Somename", "Somedata");
// processContext is a ProcessContext object
processContext.output(jsonObject.toString());
}
reader.close();

在这种情况下,文件的全部内容将在我的内存中,这会带来获取 java.lang.OutOfMemoryError 的选项。我正在寻找解决方案来一一读取所有 JSON 对象,而不将整个文件保留在我的内存中。可能的解决方案是使用对象 FileIO.ReadableFile 中的方法 open() ,该方法返回 ReadableByteChannel channel ,但我不确定如何使用该 channel 从该 channel 中专门读取一个 JSON 对象。

更新的解决方案这是我更新的解决方案,它逐行读取文件

    ReadableByteChannel readableByteChannel = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
// file is a FileIO.ReadableFile
readableByteChannel = file.open();
inputStream = Channels.newInputStream(readableByteChannel);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.length() > 1) {
// my final output should contain both filename and line
processContext.output(fileName + file);
}
}
} catch (IOException ex) {
logger.error("Exception during reading the file: {}", ex);
} finally {
IOUtils.closeQuietly(bufferedReader);
IOUtils.closeQuietly(inputStream);
}

我发现此解决方案不适用于在 n1-standard-1 计算机上运行的数据流,并会抛出 java.lang.OutOfMemoryError: 超出 GC 开销限制 异常,并且在 n1-standard-2 计算机上正常工作。

最佳答案

ReadableByteChannel 是 Java NIO API,在 Java 7 中引入。 Java provides a way将其转换为 InputStream: InputStream bis = Channels.newInputStream(file.open()); - 我相信这是您需要进行的唯一更改。

关于java - 谷歌数据流 : how to parse big file with valid JSON array from FileIO. 可读文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48618349/

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