Java大文件读取
关于逐行读取大文件 , 找了一些方法进行比较验证, 并下载了一个1.5G的access.log日志文件用来测试。
- 使用BufferedReader读取文件
- 使用 Scanner函数来读取文件
- Apache的commons-io包读取文件
使用BufferedReader读取文件
使用java.io.BufferedReader函数逐行读取,代码如下:
File file = new File(filePath);
BufferedReader buf = null;
try{
buf = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
String temp = null ;
while ((temp = buf.readLine()) != null ){
// System.out.println(temp);
}
}catch(Exception e){
e.getStackTrace();
}finally{
if(buf != null){
try{
buf.close();
} catch (IOException e) {
e.getStackTrace();
}
}
}
运行后日志
******BufferedReader 解析大文件开始******
解析文件消耗时间:2527ms
解析文件消耗内存:341MB
******BufferedReader 解析大文件结束******
使用 Scanner函数来读取文件
使用java.util.Scanner来解析文件,代码如下:
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);
}
if (sc.ioException() != null) {
throw sc.ioException();
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (sc != null) {
sc.close();
}
}
运行后日志
******Scanner 解析大文件开始******
解析文件消耗时间:22879ms
解析文件消耗内存:663MB
******Scanner 解析大文件结束******
-
使用Common-IO提供的函数
使用Apache的commons-io包逐行读取,代码如下:
LineIterator it=null;
try {
it = FileUtils.lineIterator(new File(path), "UTF-8");
while (it.hasNext()) {
String line = it.nextLine();
//System.out.println(line);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
LineIterator.closeQuietly(it);
}
运行后日志
******CommonIO 解析大文件开始******
解析文件消耗时间:2690ms
解析文件消耗内存:414MB
******CommonIO 解析大文件结束******
总结
当前使用内存相关代码:
OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long total=mem.getTotalPhysicalMemorySize() / 1024 / 1024;
long free=mem.getFreePhysicalMemorySize() / 1024 / 1024;
long user=total-free;
其中BufferedReader 和common-io使用的时间最短,消耗的内存最小。看了下FileUtils.lineIterator方法实现,也是基于BufferedReader 的。