前言
前面学会了Buffer和Channel
这里学习一个特殊的Buffer:MappedByteBuffer
概念
ByteBuffer分两种模式:直接与间接
间接的就是我们普通用的ByteBuffer,叫HeapByteBuffer,在JVM堆上,处理byte数组,但堆内存是有限的,当需要处理大文件时
使用直接模式:MappedByteBuffer,文件映射,直接调用操作系统底层的缓存(虚拟内存),没有JVM和系统之间的复制操作,MappedByteBuffer可以直接在系统底层操作文件
结构
MappedByteBuffer是一个抽象类,它的实现类是DirectByteBuffer,DirectByteBufferR继承DirectByteBuffer类
操作
FileChannel提供了map方法来把文件映射为MappedByteBuffer
可以通过RandomAccessFile随机访问文件得到FileChannel,这里“随机”是指可以跳转到文件的任意位置处读写数据
package com.company.NIOBuffer;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MappedBuffer {
public static void main(String[] args) throws Exception {
//RandomAccessFile随机访问文件
//rw设置读写
RandomAccessFile randomAccessFile = new RandomAccessFile("BasicFileChannel","rw");
//创建FileChannel
FileChannel fileChannel = randomAccessFile.getChannel();
//map映射
MappedByteBuffer mappedByteBuffer=fileChannel.map(FileChannel.MapMode.READ_WRITE,0,5);
mappedByteBuffer.put(0,(byte)'w');
mappedByteBuffer.put(3,(byte)6);
}
}
原文件:
修改后(去文件夹打开):
map映射方法
FileChannel提供了map方法来把文件映射为MappedByteBuffer,具体实现在FileChannel的实现类FileChannelImpl类
它的三个参数的作用:
- MapMode
设置读写模式,有3个值
READ_ONLY仅读
READ_WRITE读写
PRIVATE写时拷贝(copy-on-write)的映射:产生一个私有的数据拷贝并且该拷贝中的数据只有MappedByteBuffer实例可以看到,该过程不会对底层文件做任何修改
- Long var2
可以直接修改的起始地址 - Long var3
映射到内存的大小(是范围大小,不是下标)
如例中设置FileChannel.MapMode.READ_WRITE,0,5,该MappedByteBuffer可以读写,读写范围是0-4(大小为5)