How to Create and Manipulate a Memory-Mapped File in Java ?

A robust approach for mapping a portion of a file straight into memory and facilitating quick access to file contents is provided by Java's memory-mapped files. This technique improves performance while working with huge files or when it's necessary to retrieve the file data often.

Syntax:

FileChannel.map() is the main Java method used in file memory mapping. The syntax for this is as follows:

mode_name: It indicates the mapping mode, which might be PRIVATE, READ_ONLY, or READ_WRITE.

position_name: The beginning place in the file where the mapping should start.

size: The size of the mapped region.

Example 1:

Memory-mapped files can be used to change a file's content, as demonstrated by the included Java program. The first thing it does is create a RandomAccessFile for the file "HelloWorld.txt," granting read and write access. A MappedByteBuffer is then used to map the first 1024 bytes of the file into memory in read/write mode after the FileChannel has been retrieved from this file. In this memory buffer, the text "Hello, Welcome to the World!" is written, and buffer.force() makes sure the modifications are filed.

Implementation:

FileName: MemoryMappedFileExample1.java

Output:

 
File that was memory-mapped was successfully created and modified.   

Example 2:

The given Java code uses MappedByteBuffer from the java.nio package to show how to use memory-mapped files with various mapping modes (READ_WRITE, READ_ONLY, and PRIVATE). It opens a file called "HelloWorld.txt" in read-write mode, writes a string to the READ_WRITE buffer, and then divides the first 1024 bytes of the file into three buffers with various access modes. The data is next read from the READ_ONLY buffer and printed. Next, it writes to the PRIVATE buffer to keep modifications separate from those made by other processes, then reads the updated content back and prints it. This demonstrates how memory-mapped files can be utilized in Java to perform effective file I/O operations.

Implementation:

FileName: MemoryMappedPrivateReadOnlyMode.java

Output:

 
Reading from a memory-mapped file named READ_ONLY: Hello, Welcome to the World!
Reading from a memory-mapped file named PRIVATE:  This is private. the World!