gpt4 book ai didi

java - 从文件中读取特定行非常慢

转载 作者:太空宇宙 更新时间:2023-11-04 12:11:06 25 4
gpt4 key购买 nike

我创建了一种方法,可以根据行号从文件中读取特定行。它适用于大多数文件,但是当我尝试读取包含大量非常长的行的文件时,它需要很长时间,特别是当它在文件中进一步深入时。我还做了一些调试,它似乎也占用了大量内存,但我不确定这是否可以改进。我知道还有一些其他问题集中在如何从文件中读取某些行,但这个问题主要集中在性能方面。

public static final synchronized List<String> readLines(final File file, final Integer start, final Integer end) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<>();
try {
String line = bufferedReader.readLine();
Integer currentLine = 1;
while (line != null) {
if ((currentLine >= start) && (currentLine <= end)) {
lines.add(line + "\n");
}
currentLine++;
if (currentLine > end) {
return lines;
}
line = bufferedReader.readLine();
}
} finally {
bufferedReader.close();
}
return lines;
}

如何优化此方法以使其比光更快?

最佳答案

我意识到我之前所做的事情本质上很慢并且占用了太多内存。

通过将所有行添加到内存中,然后处理 List 中的所有行,不仅花费了两倍的时间,而且还无缘无故地创建了 String 变量。

我现在使用 Java 8 Stream 并在读取时进行处理,这是迄今为止我使用过的最快的方法。

Path path = Paths.get(file.getAbsolutePath());
Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8);
for (String line : (Iterable<String>) stream::iterator) {
//do stuff
}
}

关于java - 从文件中读取特定行非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39857328/

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