NIO MappedByteBuffer 作用

让文件直接在内存(堆外内存)修改,系统不需要拷贝一次

源码demo

public class MappedByteBufferDemo {
public static void main(String[] args) throws Exception {
//拿到文件
RandomAccessFile file = new RandomAccessFile("d:\\test\\1.txt", "rw");//rw:读写模式
//创建管道,把文件放入通道
FileChannel channel = file.getChannel();
//参数一:读写模式
//参数二:修改的起始位置
//参数三:映射到内存的大小(不是索引),即文件的多少个字节映射到内存。
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, 100);
map.put(0,(byte) 'A');
map.put(3,(byte) 'B');
map.put(6,(byte) 'C');

//=========== 关闭与清除 ===========
map.clear();
channel.close();
file.close();
}
}