Open In App

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

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Memory-mapped files in Java offer a powerful mechanism to map a region of a file directly into the memory providing efficient access to file data. This method enhances the performance when dealing with large files or when frequent access to the file data is required.

Syntax:

The key method involved in the memory mapping of a file in Java is FileChannel.map(). Below is the syntax for this:

public abstract MappedByteBuffer map(FileChannel.MapMode mode, long position, long size) 
throws IOException;
  • mode: It specifies the mapping mode such as READ_ONLY, READ_WRITE, or PRIVATE.
  • position: The starting position in the file at which the mapping should begin.
  • size: The size of the mapped region.

Program to Create and Manipulate a Memory-Mapped File in Java

Here’s a Java program demonstrating how to create and manipulate a memory-mapped file:

Java




// Java Program to create and manipulate
// A Memory-Mapped File
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
  
// Driver Class
public class GFG 
{
      // Main Method
    public static void main(String[] args) 
    {
        try {
            // Create a random access file
            RandomAccessFile file = new RandomAccessFile("example.txt", "rw");
            // Get the file channel in the read/write mode
            FileChannel channel = file.getChannel();
            // Map the file into memory
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
              
              buffer.put("Hello, world!".getBytes());
            buffer.force();
              
              channel.close();
              
              System.out.println("Memory-mapped file Created and Manipulated Successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output

The Memory-mapped file created and manipulated successfully.


Explanation of the Program:

  • We have created a RandomAccessFile object representing the file example.txt in the read/write mode.
  • Next, we hobtain the FileChannel associated with file to perform the channel-related operations.
  • After that by using the map() method of the FileChannel we map a region of file into the memory specifying the mapping mode, starting position and size.
  • We get a MappedByteBuffer object from the mapping in which allows us to read from and write to memory-mapped region.
  • We write the string into buffer.
  • The force() method is called to ensure that any changes made to buffer are flushed to underlying file.
  • At last, we close the file channel.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads