MappedByteBuffer

使用MappedByteBuffer可以跟方便快捷的修改文件。

/**
     * 可以让文件直接在堆外内存修改,不用再拷贝一次再修改
     */
    @Test
    public void MappedByteBufferTest() throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("e:\\111.txt", "rw");
        FileChannel fisChannel = randomAccessFile.getChannel();
        // 读写模式,从第0个下标开始,长度不能超过5个
        MappedByteBuffer mapBuf = fisChannel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
        mapBuf.put(0, (byte)'!');
//        mapBuf.put(5, (byte)'Z');// 超过长度限制会抛出java.lang.IndexOutOfBoundsException错误
        randomAccessFile.close();

    }
posted @ 2022-04-12 21:42  云扬四海  阅读(70)  评论(0编辑  收藏  举报