Dave's Brain

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

Date: 2016apr13
Language: Java

Q.  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 } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.