Memory-Mapped File Example

This program demonstrates reading a file using memory mapping.

Problem Statement

Write a Java program that maps a file into memory and reads its contents.

Source Code

1 import java.io.*;
2 import java.nio.*;
3 import java.nio.channels.*;
4 public class MemoryMappedExample {
5 public static void main(String[] args) {
6 System.out.println("Eduinq Memory Mapped Example");
7 try(RandomAccessFile raf=new RandomAccessFile("sample.txt","r");
8 FileChannel channel=raf.getChannel()) {
9 MappedByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY,0,channel.size());
10 for(int i=0;i<buffer.limit();i++){
11 System.out.print((char)buffer.get(i));
12 }
13 } catch(IOException e) {
14 System.out.println("\nEduinq Exception: "+e.getMessage());
15 }
16 }
17 }

Program Output

					Eduinq Memory Mapped Example
Hello Eduinq Welcome to File Handling
				

Explanation

Memory mapping loads file directly into memory. - Provides fast random access to file data. - Exception handling ensures safe operations. - In enterprise systems, memory mapping is used for large file processing. Conclusion: Shows reading files using memory-mapped I/O.

Quick Links to Explore