FileChannel Lock Example
This program demonstrates locking a file using FileChannel.
Problem Statement
Write a Java program that locks a file for exclusive access using FileChannel.
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.channels.*; |
| 3 | public class FileChannelLockExample { |
| 4 | public static void main(String[] args) { |
| 5 | System.out.println("Eduinq FileChannel Lock Example"); |
| 6 | try(RandomAccessFile raf=new RandomAccessFile("sample.txt","rw"); |
| 7 | FileChannel fc=raf.getChannel()) { |
| 8 | FileLock lock=fc.lock(); |
| 9 | System.out.println("Eduinq File Locked Successfully"); |
| 10 | lock.release(); |
| 11 | } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); } |
| 12 | } |
| 13 | } |
Program Output
Eduinq FileChannel Lock Example Eduinq File Locked Successfully
Explanation
Uses lock() to secure file access. - Prevents concurrent modifications. - Exception handling ensures safe operations. - In enterprise systems, locking ensures data consistency. Conclusion: Shows locking files with FileChannel.