Programming Tips - Java: How do I lock a file in Java?

Date: 2016apr13 Language: Java Q. Java: How do I lock a file in Java? A. Use lock() in FileChannel like this:
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; void lockDemo() { // 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. 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); // Unlock if (lock != null) { lock.release(); } channel.close(); } catch (Exception ex) { // Handle the exception } }