Java – Reading a Large File Efficiently--转
原文地址:http://www.baeldung.com/java-read-lines-large-file
1. Overview
This tutorial will show how to read all the lines from a large file in Java in an efficient manner.
This article is part of the “Java – Back to Basic” tutorial here on Baeldung.
2. Reading In Memory
The standard way of reading the lines of the file is in-memory – both Guava and Apache Commons IO provide a quick way to do just that:
|
1
|
Files.readLines(new File(path), Charsets.UTF_8); |
|
1
|
FileUtils.readLines(new File(path)); |
The problem with this approach is that all the file lines are kept in memory – which will quickly lead to OutOfMemoryError if the File is large enough.
For example – reading a ~1Gb file:
|
1
2
3
4
5
|
@Testpublic void givenUsingGuava_whenIteratingAFile_thenWorks() throws IOException { String path = ... Files.readLines(new File(path), Charsets.UTF_8);} |
This starts off with a small amount of memory being consumed: (~0 Mb consumed)
|
1
2
|
[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Total Memory: 128 Mb[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Free Memory: 116 Mb |
However, after the full file has been processed, we have at the end: (~2 Gb consumed)
|
1
2
|
[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Total Memory: 2666 Mb[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Free Memory: 490 Mb |
Which means that about 2.1 Gb of memory are consumed by the process – the reason is simple – the lines of the file are all being stored in memory now.
It should be obvious by this point that keeping in-memory the contents of the file will quickly exhaust the available memory – regardless of how much that actually is.
What’s more, we usually don’t need all of the lines in the file in memory at once – instead, we just need to be able to iterate through each one, do some processing and throw it away. So, this is exactly what we’re going to do – iterate through the lines without holding the in memory.
3. Streaming Through the File
Let’s now look at a solution – we’re going to use a java.util.Scanner to run through the contents of the file and retrieve lines serially, one by one:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
FileInputStream inputStream = null;Scanner sc = null;try { inputStream = new FileInputStream(path); sc = new Scanner(inputStream, "UTF-8"); 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(); }} |
This solution will iterate through all the lines in the file – allowing for processing of each line – without keeping references to them – and in conclusion, without keeping them in memory: (~150 Mb consumed)
|
1
2
|
[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Total Memory: 763 Mb[main] INFO org.baeldung.java.CoreJavaIoUnitTest - Free Memory: 605 Mb |
4. Streaming with Apache Commons IO
The same can be achieved using the Commons IO library as well, by using the customLineIterator provided by the library:
|
1
2
3
4
5
6
7
8
9
|
LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");try { while (it.hasNext()) { String line = it.nextLine(); // do something with line }} finally { LineIterator.closeQuietly(it);} |
Since the entire file is not fully in memory – this will also result in pretty conservative memory consumption numbers: (~150 Mb consumed)
|
1
2
|
[main] INFO o.b.java.CoreJavaIoIntegrationTest - Total Memory: 752 Mb[main] INFO o.b.java.CoreJavaIoIntegrationTest - Free Memory: 564 Mb |
5. Conclusion
This quick article shows how to process lines in a large file without iteratively, without exhausting the available memory – which proves quite useful when working with these large files.
The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.
Java – Reading a Large File Efficiently--转的更多相关文章
- Loading Large Bitmaps Efficiently
有效地加载大位图文件-Loading Large Bitmaps Efficiently 图像有各种不同的形状和大小.在许多情况下,他们往往比一个典型应用程序的用户界面(UI)所需要的资源更大.例如, ...
- java之io之file类的常用操作
java io 中,file类是必须掌握的.它的常用api用法见实例. package com.westward.io; import java.io.File; import java.io.IOE ...
- linux出现bash: ./java: cannot execute binary file 问题的解决办法
问题现象描述: 到orcal官网上下载了两个jdk: (1)jdk-7u9-linux-i586.tar.gz ------------>32位 (2)jdk-7u9-linux-x64.tar ...
- java: cannot execute binary file
转自:http://jxwpx.blog.51cto.com/15242/222572 java: cannot execute binary file 如果遇到这个错,一般是操作系统位数出问题了. ...
- -bash: /tyrone/jdk/jdk1.8.0_91/bin/java: cannot execute binary file
问题描述:今天在linux环境下安装了一下JDK,安装成功后,打算输入java -version去测试一下,结果却出错了. 错误信息:-bash: /tyrone/jdk/jdk1.8.0_91/bi ...
- Github Upload Large File 上传超大文件
Github中单个文件的大小限制是100MB,为了能突破这个限制,我们需要使用Git Large File Storage这个工具,参见这个官方帖子,但是按照其给的步骤,博主未能成功上传超大文件,那么 ...
- Reading Lines from File in C++
Reading Lines from File in C++ In C++, istringstream has been used to read lines from a file. code: ...
- 使用JAVA API 解析ORC File
使用JAVA API 解析ORC File orc File 的解析过程中,使用FileInputFormat的getSplits(conf, 1)函数, 然后使用 RecordReaderreade ...
- java.lang.IllegalStateException: Zip File is closed
最近在研究利用sax读取excel大文件时,出现了以下的错误: java.lang.IllegalStateException: Zip File is closed at org.apache.po ...
随机推荐
- Python(十一) 原生爬虫
一.分析抓取目的确定抓取页面 #爬取主播人气排行 二.整理爬虫常规思路 爬虫前奏 明确目的 找到数据对应的网页 分析网页的结构找到数据所在的标签位置 模拟 HTTP 请求, 向服务器发送这个请 ...
- 转:Java读写文件各种方法及性能比较
干Java这么久,一直在做WEB相关的项目,一些基础类差不多都已经忘记.经常想得捡起,但总是因为一些原因,不能如愿. 其实不是没有时间,只是有些时候疲于总结,今得空,下定决心将丢掉的都给捡起来. 文件 ...
- 分享一个vueui axios-mock-adapter 中的用法
import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { LoginUsers, Users ...
- Linux下java/bin目录下的命令集合
Linux下JAVA命令(1.7.0_79) 命令 详解 参数列表 示例 重要程度 资料 appletviewer Java applet 浏览器.appletviewer 命令可在脱离万维网浏览器环 ...
- .js控制一次加载一张图片,加载完后再加载下一张
js怎么控制一次加载一张图片,加载完后再加载下一张 (1)方法1 (1)方法2
- poj2243 && hdu1372 Knight Moves(BFS)
转载请注明出处:viewmode=contents">http://blog.csdn.net/u012860063?viewmode=contents 题目链接: POJ:http: ...
- Codeforces 474D Flowers (线性dp 找规律)
D. Flowers time limit per test:1.5 seconds memory limit per test:256 megabytes We saw the little gam ...
- windows10系统下设置mtu值的方法
windows10系统下设置mtu值的方法 http://www.xitongcheng.com/jiaocheng/win10_article_34701.html 以下为服务器上使用 ip ...
- python Tricks —— list 镜像复制与 list comprehension 列表解析的顺序
0. 对 list 镜像复制,a = [1, 2, 3] ⇒ [1, 2, 3, 3, 2, 1] a*2 ⇒ a = [1, 2, 3, 1, 2, 3] a.extend(reversed(a)) ...
- MyBatis自动生成代码之generatorConfig配置文件及其详细解读
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...