如何利用Java高效读取大文件
在内存中读取 Files.readLines(new File(path),Charsets.UTF_8);
FileUtils.readLines(new File(path)); 这类方法带来的问题是文件的所有行都被寄存在内存中,当文件足够大时很快就会致使程序抛出OutOfMemoryError 异常。 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的内存,由于文件的所有行都被存储在了内存中,把文件所有的内容都放在内存中很快会耗尽可用内存――不论实际可用内存有多大,这点是不言而喻的。 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流 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |