gpt4 book ai didi

Java在读取文件但同时使用流时避免java.lang.OutOfMemoryError

转载 作者:行者123 更新时间:2023-12-02 09:49:30 27 4
gpt4 key购买 nike

我正在尝试使用流读取一个非常大的文件,因此我需要并行流而不是每行迭代...我正在尝试如下:

String cont = new String(Files.readAllBytes(Paths.get(this.File_Path)),
StandardCharsets.UTF_8);
List<String> words = Arrays.asList(cont.split("\\PL+"));

yep = words.parallelStream()
.filter(x -> x.contains(toMatch))
.distinct()
.collect(Collectors.toList());

这适用于小文件大小,但如果我尝试对具有一些 GB 大小的文件进行相同的操作,java 会给我这个异常(exception):

java.lang.OutOfMemoryError: Required array size too large

有一种方法可以避免此异常,但同时使用并行流而不是使用 BufferReader 或 Scanner 进行迭代?

最佳答案

问题是Files.readAllBytes() 。它将文件的全部内容加载到 String 中。 ,因此在内存中。
要逐行阅读,您需要使用 Files.lines()返回 Stream<String>然后将其转换为并行流并对其进行转换操作:

List<String> words = 
Files.lines(Paths.get(this.File_Path), charSetOfYourFileIfNotUTF8) // Stream<String>
.parallel()
.flatMap(s-> Arrays.stream(s.split("\\PL+"))) // Stream<String>
.filter(x -> x.contains(toMatch))
.distinct()
.collect(Collectors.toList());

关于性能,请注意distinct()对于维护顺序的收集来说,并行管道的成本很高。
您应该考虑toSet()以进一步提高性能。

关于Java在读取文件但同时使用流时避免java.lang.OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56409936/

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