MappedByteBuffer
MappedByteBuffer可让文件直接在内存(堆外内存)中修改,操作系统不需要拷贝,而如何同步到文件由NIO来完成.
使用MappedByteBuffer来修改文件的内容:
package com.jym.nio;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* @program: JymNetty
* @description: MappedByteBuffer学习,MappedByteBuffer可让文件直接在内存(堆外内存)中修改,操作系统不需要拷贝
* @author: jym
* @create: 2020/02/01
*/
public class JymMappedByteBufferTest {
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = new RandomAccessFile("jym.txt", "rw");
FileChannel channel = randomAccessFile.getChannel();
/**
* 参数一: FileChannel.MapMode.READ_WRITE 采用的是读写模式
* 参数二: 0 可以直接修改的起始位置
* 参数三: 5 是映射内存大小(不是索引位置),即将jym.txt的多少个字节映射到内存
* 可以直接修改的范围就是 0-5
*/
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0,(byte) 'H');
mappedByteBuffer.put(3,(byte)'8');
randomAccessFile.close();
}
}