Open In App

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

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;

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 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:


Article Tags :