基于MappedByteBuffer来修改文件的内容

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();
    }
}

学习年限不足,知识过浅,说的不对请见谅。

世界上有10种人,一种是懂二进制的,一种是不懂二进制的。

发布了71 篇原创文章 · 获赞 54 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/weixin_43326401/article/details/104139069
今日推荐