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.