Modify File with MappedByteBuffer Example
This program demonstrates modifying a file using MappedByteBuffer.
Problem Statement
Write a Java program that modifies file content directly in memory using MappedByteBuffer.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class MappedModifyExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq MappedByteBuffer Modify Example"); |
| 7 | try(RandomAccessFile raf=new RandomAccessFile("sample.txt","rw"); |
| 8 | FileChannel fc=raf.getChannel()) { |
| 9 | MappedByteBuffer mbb=fc.map(FileChannel.MapMode.READ_WRITE,0,fc.size()); |
| 10 | mbb.put(0,(byte)'E'); |
| 11 | System.out.println("Eduinq File Modified Successfully"); |
| 12 | } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); } |
| 13 | } |
| 14 | } |
Program Output
Eduinq MappedByteBuffer Modify Example Eduinq File Modified Successfully
Explanation
Uses MappedByteBuffer for direct memory modification. - Updates file content instantly. - Exception handling ensures safe operations. - In enterprise systems, mapped modify supports fast updates. Conclusion: Shows modifying files with MappedByteBuffer.