基于前文对 FileChannel 核心特性(阻塞模式、内存映射、零拷贝)的解析,处理大文件(通常指几百 MB 到 GB 级别)时,传统的逐字节或小块 Buffer 读写效率极低。
针对大文件场景,FileChannel 提供了两种最高效的方案:内存映射(Memory-Mapped Files) 和 直接传输(Zero-Copy Transfer)。
一、方案一:内存映射文件(推荐用于随机读写/超大文件)
利用 MappedByteBuffer 将文件直接映射到虚拟内存,由操作系统负责分页加载。这是处理 GB 级文件最快的方式,避免了用户态与内核态的数据拷贝。
1. 读取大文件示例
importjava.io.RandomAccessFile;importjava.nio.MappedByteBuffer;importjava.nio.channels.FileChannel;importjava.nio.file.Paths;publicclassLargeFileReadDemo{publicstaticvoidmain(String[]args)throwsException{StringfilePath="large_file.dat";// 使用 RandomAccessFile 获取通道try(RandomAccessFileraf=newRandomAccessFile(filePath,"r");FileChannelchannel=raf.getChannel()){longfileSize=channel.size();// 映射整个文件到内存 (MapMode.READ_ONLY)