Open In App

How to Lock a File in Java?

In Java, file locking involves stopping processes or threads from changing a file. It comes in handy for threaded applications that require simultaneous access, to a file or to safeguard a file from modifications while it's being used by our application.

When reading or writing files we need to make sure proper file locking mechanisms are in place. This ensures data integrity in concurrent I/O-based applications.

Approach to lock a File in Java:

Program to Lock a File in Java

Here we can see one example for lock a file by using lock() method and Filechannel.

// Java program to lock a file using 
// lock() method and FileChannel
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLock {

    public static void main(String[] args) {
        String filePath = "C:\\Users\\Geeks Author\\Downloads\\geeksforgeeks.txt";

        try (RandomAccessFile file = new RandomAccessFile(filePath, "rw");
             FileChannel channel = file.getChannel()) {

            // Acquiring an exclusive lock on the file
            FileLock fileLock = channel.lock();

            System.out.println("File locked successfully");

            // Release the lock when done
            fileLock.release();
            System.out.println("File lock released.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

File locked successfully
File lock released.

Below we can refer the console output.

Output for file locked and file lock released

Explanation of the Program:

Article Tags :