MappedByteBuffer

MappedByteBuffer is a subclass of ByteBuffer that represents a memory-mapped region of a file. It allows you to read and write file contents directly in memory, enabling fast, random access to files—especially large ones.

  • Part of Java’s NIO (New I/O) system
  • Maps a region of a file into memory
  • Changes to the buffer can reflect in the file and vice versa
  • Useful in large file processing, database engines, and inter-process communication

Commonly Used Methods

Modes of Mapping (FileChannel.MapMode)

Simple Program: Reading a File with MappedByteBuffer

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class SimpleMappedByteBufferExample {
    public static void main(String[] args) throws Exception {
        RandomAccessFile file = new RandomAccessFile("sample.txt", "r");
        FileChannel channel = file.getChannel();

        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

        while (buffer.hasRemaining()) {
            System.out.print((char) buffer.get());
        }

        channel.close();
        file.close();
    }
}

The MappedByteBuffer class in Java NIO is a specialized type of ByteBuffer that allows a portion of a file to be memory-mapped, meaning it is loaded directly into memory for fast, efficient, and random-access I/O. This technique bridges the gap between file I/O and memory operations, allowing applications to read and write files as if they were working with arrays.

Created via the FileChannel.map() method, MappedByteBuffer offers several advantages:

  • High-speed access to large files without repeated I/O system calls,
  • Enables modifying files directly in memory, improving performance,
  • Suitable for memory-mapped file systems, large datasets, and data caching.

It also supports options such as READ_ONLY, READ_WRITE, and PRIVATE (copy-on-write), giving developers control over how the memory-mapped region behaves.

Scroll to Top