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