How to lock a file before writing in Java

In this article 👇

In Java, you can use the RandomAccessFile class in combination with FileChannel to lock a file before writing.

Here is an example that uses FileLock from NIO API (classes in java.nio.* package) to lock a file before writing data and then release the lock once write operation is completed:

try {
    // open file in read-write mode
    RandomAccessFile writer = new RandomAccessFile("output.txt", "rw");

    // lock file
    FileLock lock = writer.getChannel().lock();

    // wait 5s (demo purpose only)
    TimeUnit.SECONDS.sleep(5);

    // write to file
    writer.write("Hey, there!".getBytes());

    // release lock
    lock.release();

    // close the file
    writer.close();

} catch (IOException | InterruptedException ex) {
    ex.printStackTrace();
}

Now try to access the file, while it is locked, in another process:

try {
    // read all lines
    List<String> lines = Files.readAllLines(Paths.get("output.txt"));

    // print all lines
    lines.forEach(System.out::println);

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

You should see the following exception printed on the console:

java.io.IOException: The process cannot access the file because another process has locked a portion of the file
    at java.base/sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    at java.base/sun.nio.ch.FileDispatcherImpl.read(FileDispatcherImpl.java:54)
    at java.base/sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:276)
    at java.base/sun.nio.ch.IOUtil.read(IOUtil.java:245)
    ...

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.