1. java 读取大文件的困难
java 读取文件的一般操作是将文件数据全部读取到内存中,然后再对数据进行操作。例如

Path path = Paths.get("file path");
byte[] data = Files.readAllBytes(path);

这对于小文件是没有问题的,但是对于稍大一些的文件就会抛出异常

Exception in thread "main" java.lang.OutOfMemoryError: Required array size too large
at java.nio.file.Files.readAllBytes(Files.java:3156)

从错误定位看出,Files.readAllBytes 方法最大支持 Integer.MAX_VALUE - 8 大小的文件,也即最大2GB的文件。一旦超过了这个限度,java 原生的方法就不能直接使用了。

2. 分次读取大文件
既然不能直接全部读取大文件到内存中,那么就应该把文件分成多个子区域分多次读取。这就会有多种方法可以使用。

(1) 文件字节流
对文件建立 java.io.BufferedInputStream ,每次调用 read() 方法时会接连取出文件中长度为 arraySize 的数据到 array 中。这种方法可行但是效率不高。

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException; /**
* Created by zfh on 16-4-19.
*/
public class StreamFileReader {
private BufferedInputStream fileIn;
private long fileLength;
private int arraySize;
private byte[] array; public StreamFileReader(String fileName, int arraySize) throws IOException {
this.fileIn = new BufferedInputStream(new FileInputStream(fileName), arraySize);
this.fileLength = fileIn.available();
this.arraySize = arraySize;
} public int read() throws IOException {
byte[] tmpArray = new byte[arraySize];
int bytes = fileIn.read(tmpArray);// 暂存到字节数组中
if (bytes != -1) {
array = new byte[bytes];// 字节数组长度为已读取长度
System.arraycopy(tmpArray, 0, array, 0, bytes);// 复制已读取数据
return bytes;
}
return -1;
} public void close() throws IOException {
fileIn.close();
array = null;
} public byte[] getArray() {
return array;
} public long getFileLength() {
return fileLength;
} public static void main(String[] args) throws IOException {
StreamFileReader reader = new StreamFileReader("/home/zfh/movie.mkv", 65536);
long start = System.nanoTime();
while (reader.read() != -1) ;
long end = System.nanoTime();
reader.close();
System.out.println("StreamFileReader: " + (end - start));
}
}

(2) 文件通道
对文件建立 java.nio.channels.FileChannel ,每次调用 read() 方法时会先将文件数据读取到分配的长度为 arraySize 的 java.nio.ByteBuffer 中,再从中将已经读取到的文件数据转化到 array 中。这种利用了NIO中的通道的方法,比传统的字节流读取文件是要快一些。

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; /**
* Created by zfh on 16-4-18.
*/
public class ChannelFileReader {
private FileInputStream fileIn;
private ByteBuffer byteBuf;
private long fileLength;
private int arraySize;
private byte[] array; public ChannelFileReader(String fileName, int arraySize) throws IOException {
this.fileIn = new FileInputStream(fileName);
this.fileLength = fileIn.getChannel().size();
this.arraySize = arraySize;
this.byteBuf = ByteBuffer.allocate(arraySize);
} public int read() throws IOException {
FileChannel fileChannel = fileIn.getChannel();
int bytes = fileChannel.read(byteBuf);// 读取到ByteBuffer中
if (bytes != -1) {
array = new byte[bytes];// 字节数组长度为已读取长度
byteBuf.flip();
byteBuf.get(array);// 从ByteBuffer中得到字节数组
byteBuf.clear();
return bytes;
}
return -1;
} public void close() throws IOException {
fileIn.close();
array = null;
} public byte[] getArray() {
return array;
} public long getFileLength() {
return fileLength;
} public static void main(String[] args) throws IOException {
ChannelFileReader reader = new ChannelFileReader("/home/zfh/movie.mkv", 65536);
long start = System.nanoTime();
while (reader.read() != -1) ;
long end = System.nanoTime();
reader.close();
System.out.println("ChannelFileReader: " + (end - start));
}
}

(3) 内存文件映射
这种方法就是把文件的内容被映像到计算机虚拟内存的一块区域,从而可以直接操作内存当中的数据而无需每次都通过 I/O 去物理硬盘读取文件。这是由当前 java 态进入到操作系统内核态,由操作系统读取文件,再返回数据到当前 java 态的过程。这样就能大幅提高我们操作大文件的速度。

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel; /**
* Created by zfh on 16-4-19.
*/
public class MappedFileReader {
private FileInputStream fileIn;
private MappedByteBuffer mappedBuf;
private long fileLength;
private int arraySize;
private byte[] array; public MappedFileReader(String fileName, int arraySize) throws IOException {
this.fileIn = new FileInputStream(fileName);
FileChannel fileChannel = fileIn.getChannel();
this.fileLength = fileChannel.size();
this.mappedBuf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);
this.arraySize = arraySize;
} public int read() throws IOException {
int limit = mappedBuf.limit();
int position = mappedBuf.position();
if (position == limit) {
return -1;
}
if (limit - position > arraySize) {
array = new byte[arraySize];
mappedBuf.get(array);
return arraySize;
} else {// 最后一次读取数据
array = new byte[limit - position];
mappedBuf.get(array);
return limit - position;
}
} public void close() throws IOException {
fileIn.close();
array = null;
} public byte[] getArray() {
return array;
} public long getFileLength() {
return fileLength;
} public static void main(String[] args) throws IOException {
MappedFileReader reader = new MappedFileReader("/home/zfh/movie.mkv", 65536);
long start = System.nanoTime();
while (reader.read() != -1);
long end = System.nanoTime();
reader.close();
System.out.println("MappedFileReader: " + (end - start));
}
}

看似问题完美解决了,我们肯定会采用内存文件映射的方法去处理大文件。但是运行结果发现,这个方法仍然不能读取超过2GB的文件,明明 FileChannel.map() 方法传递的文件长度是 long 类型的,怎么和 Integer.MAX_VALUE 有关系?

Exception in thread "main" java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:868)

再从错误定位可以看到

size - The size of the region to be mapped; must be non-negative and no greater than Integer.MAX_VALUE

这可以归结到一些历史原因,还有 int 类型在 java 中的深入程度,但是本质上由于 java.nio.MappedByteBuffer 是直接继承自 java.nio.ByteBuffer 的,而后者的索引变量是 int 类型的,所以前者也只能最大索引到 Integer.MAX_VALUE 的位置。这样的话我们是不是就没有办法了?当然不是,一个内存文件映射不够用,那么试一试用多个就可以了。

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel; /**
* Created by zfh on 16-4-19.
*/
public class MappedBiggerFileReader {
private MappedByteBuffer[] mappedBufArray;
private int count = 0;
private int number;
private FileInputStream fileIn;
private long fileLength;
private int arraySize;
private byte[] array; public MappedBiggerFileReader(String fileName, int arraySize) throws IOException {
this.fileIn = new FileInputStream(fileName);
FileChannel fileChannel = fileIn.getChannel();
this.fileLength = fileChannel.size();
this.number = (int) Math.ceil((double) fileLength / (double) Integer.MAX_VALUE);
this.mappedBufArray = new MappedByteBuffer[number];// 内存文件映射数组
long preLength = 0;
long regionSize = (long) Integer.MAX_VALUE;// 映射区域的大小
for (int i = 0; i < number; i++) {// 将文件的连续区域映射到内存文件映射数组中
if (fileLength - preLength < (long) Integer.MAX_VALUE) {
regionSize = fileLength - preLength;// 最后一片区域的大小
}
mappedBufArray[i] = fileChannel.map(FileChannel.MapMode.READ_ONLY, preLength, regionSize);
preLength += regionSize;// 下一片区域的开始
}
this.arraySize = arraySize;
} public int read() throws IOException {
if (count >= number) {
return -1;
}
int limit = mappedBufArray[count].limit();
int position = mappedBufArray[count].position();
if (limit - position > arraySize) {
array = new byte[arraySize];
mappedBufArray[count].get(array);
return arraySize;
} else {// 本内存文件映射最后一次读取数据
array = new byte[limit - position];
mappedBufArray[count].get(array);
if (count < number) {
count++;// 转换到下一个内存文件映射
}
return limit - position;
}
} public void close() throws IOException {
fileIn.close();
array = null;
} public byte[] getArray() {
return array;
} public long getFileLength() {
return fileLength;
} public static void main(String[] args) throws IOException {
MappedBiggerFileReader reader = new MappedBiggerFileReader("/home/zfh/movie.mkv", 65536);
long start = System.nanoTime();
while (reader.read() != -1) ;
long end = System.nanoTime();
reader.close();
System.out.println("MappedBiggerFileReader: " + (end - start));
}
}

3. 运行结果比较
用上面三种方法读取1GB文件,运行结果如下

StreamFileReader: 11494900386
ChannelFileReader: 11329346316
MappedFileReader: 11169097480

读取10GB文件,运行结果如下

StreamFileReader: 194579779394
ChannelFileReader: 190430242497
MappedBiggerFileReader: 186923035795

————————————————
原文链接:https://blog.csdn.net/zhufenghao/article/details/51192043

java 分批次读取大文件的三种方法的更多相关文章

  1. java 分次读取大文件的三种方法

    1. java 读取大文件的困难 java 读取文件的一般操作是将文件数据全部读取到内存中,然后再对数据进行操作.例如 Path path = Paths.get("file path&qu ...

  2. PHP读取大文件的几种方法介绍

    读取大文件一直是一个头痛的问题,我们像使用php开发读取小文件可以直接使用各种函数实现,但一到大文章就会发现常用的方法是无法正常使用或时间太长太卡了,下面我们就一起来看看关于php读取大文件问题解决办 ...

  3. .NET读取Excel文件的三种方法的区别

    ASP.NET读取Excel文件方法一:采用OleDB读取Excel文件: 把Excel文件当做一个数据源来进行数据的读取操作,实例如下: public DataSet ExcelToDS(strin ...

  4. 【转】flash air中读取本地文件的三种方法

    actionscript中读取本地文件操作有两种代码如下 1.使用File和FileStream两个类,FileStream负责读取数据的所以操作:(同步操作) var stream:FileStre ...

  5. PHP读取大文件的几种方法

    场景:PHP读取超大文件,例如1G的日志文件,我这里使用的是400M的access.log文件 1.使用file直接读取 <?php $starttime=microtime_float(); ...

  6. java使用java.util.Properties读取properties文件的九种方法

    直接上代码: package com.test.test; import java.io.BufferedInputStream; import java.io.FileInputStream; im ...

  7. PHP读取远程文件的三种方法

    file_get_contents <?php$url = http://www.xxx.com/;$contents = file_get_contents($url);//如果出现中文乱码使 ...

  8. java分享第十六天( java读取properties文件的几种方法&java配置文件持久化:static块的作用)

     java读取properties文件的几种方法一.项目中经常会需要读取配置文件(properties文件),因此读取方法总结如下: 1.通过java.util.Properties读取Propert ...

  9. matlab读取cvs文件的几种方法

    matlab读取CVS文件的几种方法: 1,实用csvread()函数   csvread()函数有三种使用方法: 1.M = csvread('filename')2.M = csvread('fi ...

  10. VC中加载LIB库文件的三种方法

    VC中加载LIB库文件的三种方法 在VC中加载LIB文件的三种方法如下: 方法1:LIB文件直接加入到工程文件列表中   在VC中打开File View一页,选中工程名,单击鼠标右键,然后选中&quo ...

随机推荐

  1. 链表的创建&遍历打印

    博客地址:https://www.cnblogs.com/zylyehuo/ # -*- coding: utf-8 -*- class Node: def __init__(self, item): ...

  2. 插入排序(LOW)

    博客地址:https://www.cnblogs.com/zylyehuo/ # _*_coding:utf-8_*_ def insert_sort(li): for i in range(1, l ...

  3. substring( )的两种用法?

    xx.substring()括号中带的参数不一样,效果就会有很大的区别 1.xx.substring(0,2)表示取第一个和第二个字符(0,1,2表示第一.二.三个字符,含头不含尾的原则就只包含第一. ...

  4. C# 多文件打包

    public HttpResponseMessage GetZip() { var response = Request.CreateResponse(HttpStatusCode.OK); try ...

  5. SQLServer中事务处理

    --将当前库存记录insert医废转移单中 --declare @Warehouse nvarchar(100); declare @Warehouse_JJRID nvarchar(100); de ...

  6. idea远程访问docker查看控制台中文乱码问题

    今天心血来潮想把自己的项目部署到docker,部署完成后通过idea远程访问docker.发现控制台日志出现中文乱码,起初还以为docker或者项目编码没有设置好,一一排查后发现服务器编码和环境都没有 ...

  7. ShadowSql之精简版拆分

    ShadowSql拆分为精简版和易用版,项目和nuget包同步拆分 ShadowSql项目拆分为ShadowSql.Core和ShadowSql Dapper.Shadow项目拆分为Dapper.Sh ...

  8. 测试用例Xmind转XML格式教程

    运行环境: Python版本:3.7(Python2.x和Python2.x均可) 第三方库:xmind2testlink/xmind2testcase 1.安装Python(以Python3.x为例 ...

  9. 基于华为交换机的三层Clos架构(Leaf-Spine)配置指南

    基于华为交换机的三层Clos架构(Leaf-Spine)配置指南 目录 设计原则 配置步骤 物理连接与基础配置 路由协议配置 VXLAN+EVPN配置 M-LAG高可用配置 BFD快速检测 验证命令 ...

  10. MySQL 中使用索引一定有效吗?如何排查索引效果?

    MySQL 中使用索引一定有效吗?如何排查索引效果? 虽然索引是提升 MySQL 查询性能的常见手段,但并不是所有情况下索引都会有效.索引的使用取决于查询条件.数据分布.索引设计等多个因素.如果索引未 ...