Date: 2016apr13
Update: 2025oct21
Language: Java
Q. Java: How to lock a file in Java
A. Use lock() in FileChannel as shown in this full example:
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.channels.FileChannel;
import java.nio.channels.OverlappingFileLockException;
import java.io.IOException;
class Demo {
static void doSomething(RandomAccessFile raf, final String filename) {
System.out.println("I have a lock of " + filename);
}
public static final void main(String []args) {
// You might want to check that the file exists now and make an empty one.
// You can't lock a file that doesn't exist. See my touch() function.
String filename = "/tmp/myfile.txt";
try {
File file = new File(filename);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
// Warning: lock() will block so you might want to use tryLock()
FileLock lock = channel.lock();
// We got the lock!
doSomething(raf, filename);
// Unlock
if (lock != null) {
lock.release();
}
channel.close();
} catch (Exception ex) {
System.out.println("Could not lock " + filename + " because " + ex.getMessage());
}
}
}
Output:
I have a lock of /tmp/myfile.txt