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