您的位置:首页 > 编程语言 > Java开发

Java大文件读取的几种方法

2017-09-27 16:57 363 查看

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();
}
}
}


运行后日志

[b]******BufferedReader 解析大文件开始******[/b]

解析文件消耗时间:2527ms

解析文件消耗内存:341MB

[b]******BufferedReader 解析大文件结束******[/b]

使用 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();
}
}


运行后日志

[b]******Scanner 解析大文件开始******[/b]

解析文件消耗时间:22879ms

解析文件消耗内存:663MB

[b]******Scanner 解析大文件结束******[/b]

-

使用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);
}


运行后日志

[b]******CommonIO 解析大文件开始******[/b]

解析文件消耗时间:2690ms

解析文件消耗内存:414MB

[b]******CommonIO 解析大文件结束******[/b]

总结

当前使用内存相关代码:

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 的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: