NIO之MappedByteBuffer的使用

865 阅读1分钟

NIO提供了MappedByteBuffer,可以让文件直接在内存(堆外内存)中进行修改,而如何同步到文件由NIO来完成。

下面我们来看看一个例子
先创建一个文件1.txt,里面的内容为hello world

1hello word!

编写一个程序对文件内容进行修改
public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException;
参数解释:

参数 解释
mode 使用的读写模式
position 可以直接修改的起始位置
size 映射到内存的大小,即将1.txt的多少个字节映射到内存

MapMode对应的模式

模式 解释
FileChannel.MapMode.READ_ONLY 只可读映射,如果进行写操作会抛出异常
FileChannel.MapMode.READ_WRITE 读写映射,对缓存区的修改最终会写入文件
FileChannel.MapMode.PRIVATE 读写映射,只对缓冲区修改,但是不会写入文件

 1    @Test
2    public void test2() throws Exception{
3        RandomAccessFile rw = new RandomAccessFile("1.txt""rw");
4        FileChannel rwChannel = rw.getChannel();
5
6        MappedByteBuffer mappedByteBuffer = rwChannel.map(FileChannel.MapMode.READ_WRITE, 05);
7        mappedByteBuffer.put(0, (byte)'H');
8        mappedByteBuffer.put(3, (byte)'9');
9
10        rw.close();
11        rwChannel.close();
12
13    }

运行后文件内容如下

1Hel9o word!

可以看出,文件相应的字符已经被修改了。