基于java的NIO的java.nio.MappedByteBuffer大文件读取对文本文件读取一半数据进行打印分析,具体如下所示
import java.io.File;@b@import java.io.FileNotFoundException;@b@import java.io.IOException;@b@import java.io.RandomAccessFile;@b@import java.nio.MappedByteBuffer;@b@import java.nio.channels.FileChannel;@b@@b@ @b@public class FileRandomAccessUtil {@b@@b@ public static void autoCompleteSingleFieldWarp() {@b@ final int BUFFER_SIZE = 0x300000;// 缓冲区大小为3M@b@ File f = new File("C:\\WS\\NJ\\readme.txt");@b@ MappedByteBuffer inputBuffer;@b@ RandomAccessFile raf = null;@b@ try {@b@ raf = new RandomAccessFile(f, "r");@b@ inputBuffer = raf.getChannel().map(FileChannel.MapMode.READ_ONLY,@b@ f.length() / 2, f.length() / 2);@b@ byte[] dst = new byte[BUFFER_SIZE];// 每次读出3M的内容@b@ long start = System.currentTimeMillis();@b@ for (int offset = 0; offset < inputBuffer.capacity(); offset += BUFFER_SIZE) {@b@ if (inputBuffer.capacity() - offset >= BUFFER_SIZE) {@b@ for (int i = 0; i < BUFFER_SIZE; i++)@b@ dst[i] = inputBuffer.get(offset + i);@b@ } else {@b@ for (int i = 0; i < inputBuffer.capacity() - offset; i++)@b@ dst[i] = inputBuffer.get(offset + i);@b@ }@b@ int length = (inputBuffer.capacity() % BUFFER_SIZE == 0) ? BUFFER_SIZE@b@ : inputBuffer.capacity() % BUFFER_SIZE;@b@ System.out.println(new String(dst, 0, length));// new@b@ }@b@ long end = System.currentTimeMillis();@b@ System.out.println("读取文件文件一半内容花费:" + (end - start) + "毫秒");@b@ } catch (FileNotFoundException e) {@b@ e.printStackTrace();@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ } finally {@b@ if (raf != null)@b@ try {@b@ raf.close();@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ }@b@ @b@ public static void main(String[] args){@b@ autoCompleteSingleFieldWarp();@b@ }@b@@b@}
控制台打印结果如下
strength.@b@ @b@ @b@<Station principle>@b@@b@ Steadfast personhood, attentively work, the good faith defends the promise, the user is supreme@b@ @b@ @b@<Contact information>@b@@b@ Message board, mailbox(394345319@qq.com@b@读取文件文件一半内容花费:0毫秒