使用 Java NIO 读取大文件

Read A Large File Using Java NIO

我需要读取一个大文件的内容。为此,我用谷歌搜索了一下,发现了很多方法和资源。但是我仍然很困惑读取大文件的方法是什么(我的情况需要考虑的因素是内存分配、性能、大文件)

  1. 使用FileChannel
  2. 使用Files.readAllLines
  3. 使用BufferedReader

有人可以指导吗?

你最好的选择是懒惰地阅读文件。一次获取每一行并进行处理。

示例:-

Stream<String> lines = Files.lines(Paths.get("C:/files", "yourfile.txt"));

然后处理后面的行。

来自 official 文档:-

public static Stream<String> lines(Path path, Charset cs) throws IOException

Read all lines from a file as a Stream. Unlike readAllLines, this method does not read all lines into a List, but instead populates lazily as the stream is consumed.