首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Java逐行读取大型文本文件?

如何使用Java逐行读取大型文本文件?
EN

Stack Overflow用户
提问于 2011-05-03 18:53:24
回答 22查看 1.3M关注 0票数 939

我需要使用Java逐行读取一个大约5-6 GB的大文本文件。

我怎样才能快速完成这项工作?

EN

回答 22

Stack Overflow用户

发布于 2011-05-03 19:07:14

一种常见的模式是使用

代码语言:javascript
运行
复制
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.
    }
}

如果假设没有字符编码,则可以更快地读取数据。例如ASCII-7,但它不会有太大的不同。您对数据所做的操作很可能需要更长的时间。

EDIT:一种不太常见的模式,可避免line泄漏的范围。

代码语言:javascript
运行
复制
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    for(String line; (line = br.readLine()) != null; ) {
        // process the line.
    }
    // line is not visible here.
}

更新:在Java 8中,您可以做到

代码语言:javascript
运行
复制
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
        stream.forEach(System.out::println);
}

注意:您必须将流放在try-with-resource块中,以确保在其上调用#close方法,否则底层文件句柄永远不会关闭,直到GC很久以后才会关闭。

票数 1.2K
EN

Stack Overflow用户

发布于 2011-05-03 18:57:10

看看这篇博客:

  • Java Read File Line by Line - Java Tutorial

可以指定缓冲区大小,也可以使用默认大小。对于大多数用途来说,默认值已经足够大了。

代码语言:javascript
运行
复制
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
}

//Close the input stream
fstream.close();
票数 172
EN

Stack Overflow用户

发布于 2013-07-26 02:58:39

一旦Java 8发布(2014年3月),您将能够使用streams:

代码语言:javascript
运行
复制
try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
  lines.forEachOrdered(line -> process(line));
}

打印文件中的所有行:

代码语言:javascript
运行
复制
try (Stream<String> lines = Files.lines(file, Charset.defaultCharset())) {
  lines.forEachOrdered(System.out::println);
}
票数 117
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5868369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档