Java – How to lock a file before writing

In Java, we can combine RandomAccessFile and FileChannel to lock a file before writing.

LockFileAndWrite.java

package com.mkyong;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.concurrent.TimeUnit;

public class LockFileAndWrite {

    public static void main(String[] args) {

        writeFileWithLock(new File("D:\\server.log"), "mkyong");

    }

    public static void writeFileWithLock(File file, String content) {

		// auto close and release the lock
        try (RandomAccessFile reader = new RandomAccessFile(file, "rw");
             FileLock lock = reader.getChannel().lock()) {
 
            // Simulate a 10s locked
            TimeUnit.SECONDS.sleep(10);

            reader.write(content.getBytes());

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

    }

}

While the file is locked, try to read it in another process:


	try {
		List<String> lines = Files.readAllLines(Paths.get("D:\\server.log"));
		lines.forEach(x -> System.out.println(x));
	} catch (IOException e) {
		e.printStackTrace();
	}

Output


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)
	at java.base/sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:223)
	at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:65)
	at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:109)
	at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:103)
	at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
	at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
	at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
	at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
	at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
	at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
	at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3405)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3442)
	at com.mkyong.TestFile.main(TestFile.java:19)

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar