gpt4 book ai didi

Java 读取 7000 万行文本的大型文本文件

转载 作者:IT老高 更新时间:2023-10-28 20:53:19 24 4
gpt4 key购买 nike

我有一个包含 7000 万行文本的大型测试文件。我必须逐行读取文件。

我使用了两种不同的方法:

InputStreamReader isr = new InputStreamReader(new FileInputStream(FilePath),"unicode");
BufferedReader br = new BufferedReader(isr);
while((cur=br.readLine()) != null);

LineIterator it = FileUtils.lineIterator(new File(FilePath), "unicode");
while(it.hasNext()) cur=it.nextLine();

是否有另一种方法可以使这项任务更快?

最佳答案

1) 我确信在速度上没有区别,两者都在内部使用 FileInputStream 和缓冲

2) 您可以自己测量并查看

3) 虽然没有性能优势,但我喜欢 1.7 方法

try (BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"), StandardCharsets.UTF_8)) {
for (String line = null; (line = br.readLine()) != null;) {
//
}
}

4) 基于扫描仪的版本

    try (Scanner sc = new Scanner(new File("test.txt"), "UTF-8")) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
}

5) 这可能比其他的更快

try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
ByteBuffer bb = ByteBuffer.allocateDirect(1000);
for(;;) {
StringBuilder line = new StringBuilder();
int n = ch.read(bb);
// add chars to line
// ...
}
}

它需要一些编码,但由于 ByteBuffer.allocateDirect,它可以真正更快。它允许操作系统直接从文件中读取字节到ByteBuffer,而不需要复制

6) 并行处理肯定会提高速度。创建一个大字节缓冲区,运行多个任务,从文件中并行读取字节到该缓冲区,当准备好找到第一个行尾时,创建一个 String,找到下一个...

关于Java 读取 7000 万行文本的大型文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14037404/

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