What is a Memory-Mapped File in Java?

Memory-Mapped File

A MappedByteBuffer is created when a file is mapped into memory when the operating system loads the contents of the file into the process' virtual memory. With the help of MemoryMapped files, the application can read and write data from files. The buffer's modifications are automatically synchronized with those made to the underlying file.

How Memory-Mapped Files Work?

The operating system loads a file's contents into the process' virtual memory when it maps a file to memory, forming a structure called MappedByteBuffer. Similar to using a regular byte array, this buffer enables the application to read from and write to the file directly.

Without the requirement for explicit read or write operations, modifications done inside the buffer are automatically synchronized with the underlying file and vice versa.

File Name: MemoryMappedFileExample.java

Output:

 
Read from memory-mapped file: Hello, Memory-Mapped File!   

example.txt

Explanation

It begins by using RandomAccessFile to open a file in read/write mode. Next, it uses getChannel() to retrieve the file's channel. After being defined, the string "Hello, Memory-Mapped File!" is transformed into a byte array (dataBytes).

In order to make sure the memory buffer can hold the data without raising a BufferOverflowException, the file size is configured to match the length of dataBytes. The file is subsequently mapped into memory using map on the FileChannel.

The dataBytes are extended from position 0 to the end in MapPath.READ_WRITE mode. Position (0) is used to reset the buffer's position so that it can be read from the beginning. Put is used to write data to the buffer.

To verify that the process was successful, the data is read back into a fresh byte array (readData) and written out. In the finally block, resources are securely closed to stop resource leaks.


Next TopicAscii