MappedByteBuffer Read Example
This program demonstrates reading a file using MappedByteBuffer.
Problem Statement
Write a Java program that reads data from a file using MappedByteBuffer.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class MappedReadExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq MappedByteBuffer Read Example"); |
| 7 | try(RandomAccessFile raf=new RandomAccessFile("sample.txt","r"); |
| 8 | FileChannel fc=raf.getChannel()) { |
| 9 | MappedByteBuffer mbb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size()); |
| 10 | for(int i=0;i<mbb.limit();i++){ |
| 11 | System.out.print((char)mbb.get(i)); |
| 12 | } |
| 13 | } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); } |
| 14 | } |
| 15 | } |
Program Output
Eduinq MappedByteBuffer Read Example (sample.txt content displayed)
Explanation
Uses MappedByteBuffer for memory-mapped I/O. - Reads file directly into memory. - Exception handling ensures safe operations. - In enterprise systems, memory mapping speeds up large file access. Conclusion: Shows reading with MappedByteBuffer.