MappedByteBuffer介绍
MappedByteBuffer与ByteBuffer关系
MappedByteBuffer是继承ByteBuffer的,MappedByteBuffer下有又如下实现类
MappedByteBuffer优点
MappedByteBuffer可以让文件直接在内存中修改(堆外内存)操作系统不需要再次拷贝,而如何同步到文件由NIO 来完成,MappedByteBuffer性能是比较高的
实例代码
/**
* @description: MappedByteBuffer 可以让文件直接在内存中修改(对外内存),操作系统不需要拷贝一次
* @author TAO
* @date 2021/6/23 2:17
*/
public class MappedByteBufferTest {
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = new RandomAccessFile("MappedByteBuffer.txt", "rw");
//对应的通道
FileChannel channel = randomAccessFile.getChannel();
/**
*参数1 :FileChannel.MapMode.READ_WRITE 使用的读写模式
*参数2 0: 可以直接修改的起始位置
*参数3 5: 是映射到内存的大小(不是索引位置),即将MappedByteBuffer.txt 的多少个直接映射到内存
*可以直接修改的范围是0-5
*实际类型 DirectByteBuffer
*/
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0,(byte) 100);
mappedByteBuffer.put(3, (byte) '9');
randomAccessFile.close();
System.out.println("修改成功!");
}
}