程序员人生 网站导航

如何利用Java高效读取大文件

栏目:php教程时间:2015-04-13 08:33:43

在内存中读取
读取文件行的标准方式是在内存中读取,Guava 和Apache Commons IO都提供了以下所示快速读取文件行的方法:

Files.readLines(new File(path), Charsets.UTF_8); FileUtils.readLines(new File(path));

这类方法带来的问题是文件的所有行都被寄存在内存中,当文件足够大时很快就会致使程序抛出OutOfMemoryError 异常。
读取1个大约1G的文件

public void readFiles() throws IOException { String path = "..."; Files.readLines(new File(path), Charsets.UTF_8); }

这类方式刚开始只占用了很少许的内存,但是,当文件全部读入内存后,我们可以看到,占用了大量的内存(约2个G)

[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Total Memory: 2666 Mb [main] INFO org.baeldung.java.CoreJavaIoUnitTest - Free Memory: 490 Mb

这意味着这1进程消耗了大约2.1G的内存,由于文件的所有行都被存储在了内存中,把文件所有的内容都放在内存中很快会耗尽可用内存――不论实际可用内存有多大,这点是不言而喻的。
另外,我们通常不需要把文件的所有行1次性地放入内存中――相反,我们只需要遍历文件的每行,然后做相应的处理,处理完以后把它扔掉。所以,这正是我们将要做的――通过行迭代,而不是把所有行都放在内存中。
文件流
现在我们来看看下面这类解决方法,我们用Java.util.Scanner 扫描文件的每行,1行1行连续的读取:

FileInputStream inputStream = null; Scanner sc = null; try { inputStream = new FileInputStream(path); sc = new Scanner(inputStream, "UTF⑻"); while (sc.hasNextLine()) { String line = sc.nextLine(); // System.out.println(line); } // note that Scanner suppresses exceptions if (sc.ioException() != null) { throw sc.ioException(); } } finally { if (inputStream != null) { inputStream.close(); } if (sc != null) { sc.close(); } }

这类方案会遍历文件中的所有行,允许对每行进行处理,而不保持对它的援用,总之没有把他们寄存在内存中,我们可以看到,大约消耗了150MB内存。

[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Total Memory: 763 Mb [main] INFO org.baeldung.java.CoreJavaIoUnitTest - Free Memory: 605 Mb

Apache Commons IO流
一样可使用Commons IO流,利用该库提供的自定义 LineIterator类:

LineIterator it = FileUtils.lineIterator(theFile, "UTF⑻"); try { while (it.hasNext()) { String line = it.nextLine(); // do something with line } } finally { LineIterator.closeQuietly(it); }

一样也消耗了相当少的内存,大约150M:

[main] INFO o.b.java.CoreJavaIoIntegrationTest - Total Memory: 752 Mb [main] INFO o.b.java.CoreJavaIoIntegrationTest - Free Memory: 564 Mb
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐