NIO学习(十二):Java NIO的MappedByteBuffer的简单使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/outsanding/article/details/102737265
背景
  1. 把磁盘上的文件映射到内存中,在内存中直接修改内容,磁盘上的文件内容也随之更改。

MappedByteBuffer
  1. 准备一个文件mappedbytebuffer.txt,内容为aaaaaa
  2. 测试代码
public static void main(String[] args) throws Exception{
        RandomAccessFile randomAccessFile = new RandomAccessFile("mappedbytebuffer.txt", "rw");

        FileChannel fileChannel = randomAccessFile.getChannel();

        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 6);

        mappedByteBuffer.put(0, (byte)'c');
        mappedByteBuffer.put(3, (byte)'c');


    }
  1. 测试结果(使用其他文本编辑器打开)
    在这里插入图片描述
    第0个位置和第3个位置被修改为c了。

小结
  1. MappedByteBuffer的简单使用。

猜你喜欢

转载自blog.csdn.net/outsanding/article/details/102737265