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)

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

    // release lock

    // close the file

} catch (IOException | InterruptedException ex) {

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

} catch (IOException ex) {

You should see the following exception printed on the console: The process cannot access the file because another process has locked a portion of the file
    at java.base/ Method)
    at java.base/
    at java.base/
    at java.base/

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.