FileLock in Java NIO Channels
FileLock locks or tries to lock the given part of the file. It belongs to the package java.nio.channels and this feature is available in java from JDK 1.4.
FileLock is used for locking the files in either shared mode or non-shared mode. It has two important methods as given below:
- FileLock.lock(long position, long size, boolean shared)
- FileLock.tryLock(long position, long size, boolean shared)
The above method uses the argument as initial position, file size to lock and one more parameter to decide whether a lock is shared or not.
Creating a file lock
The object of file-lock is created when the lock is acquired on a file using one of the lock() or tryLock() methods of the FileChannel or AsynchronousFileChannel.
Basic FileLock Example
Let’s see the program used to write (append) in a file using the channel with exclusive lock:
FileLockExample.java
PrintFile.java
Note: Before running the code a text file named as “testout.txt” is need to be created and the content of a text file is given below:
Welcome to tutoraspire.com
This is the example of FileLock in Java NIO channel.
Output: