在 Java 里,“NIO 内存映射”一般指 MappedByteBuffer,也就是把文件直接映射到内存中,通过内存操作来完成文件读写,效率比普通 IO 高很多(尤其是大文件)。
下面从 概念 → 步骤 → 示例 → 注意事项 给你讲清楚。
FileChannel:文件通道MappedByteBuffer:内存映射缓冲区FileChannel.MapMode):
READ_ONLY:只读READ_WRITE:读写(写会同步到文件)PRIVATE:私有副本(不写回文件)RandomAccessFile 或 FileInputStream / FileOutputStream)FileChannelchannel.map()import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MmapRead {
public static void main(String[] args) throws Exception {
try (RandomAccessFile file = new RandomAccessFile("test.txt", "r");
FileChannel channel = file.getChannel()) {
MappedByteBuffer buffer = channel.map(
FileChannel.MapMode.READ_ONLY,
0,
channel.size()
);
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
}
}
}
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MmapWrite {
public static void main(String[] args) throws Exception {
try (RandomAccessFile file = new RandomAccessFile("test.txt", "rw");
FileChannel channel = file.getChannel()) {
MappedByteBuffer buffer = channel.map(
FileChannel.MapMode.READ_WRITE,
0,
1024 // 映射 1KB
);
buffer.put("Hello MappedByteBuffer".getBytes());
}
}
}
✅ 写完后,内容会自动同步到文件(由 OS 控制时机)
map() 不能直接映射超过 Integer.MAX_VALUE 的文件,要分块:
long fileSize = channel.size();
long position = 0;
long mapSize = 1024 * 1024 * 100; // 100MB
while (position < fileSize) {
long size = Math.min(mapSize, fileSize - position);
MappedByteBuffer buffer = channel.map(
FileChannel.MapMode.READ_ONLY,
position,
size
);
// 处理 buffer
position += size;
}
close() 方法Cleanerjava.io.IOException: Too many open files
✅ 手动释放(不推荐但可用):
((DirectBuffer) buffer).cleaner().clean();
buffer.force();
mapSize 是 int✅ 适合:
❌ 不适合:
如果你愿意,我可以:
你更想看哪一个?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。