How to Lock a File

3 years ago by in How To, IO Tagged: , ,

Locking a file is quite simple in Java. The FileChannel (Java Doc) provides all methods we need to lock files. The tryLock() (Java Doc) method will try to obtain the lock on the file without waiting. If the lock is acquired an instance of FileLock (Java Doc) is returned, otherwise this method returns null.

The following example shows how to obtain a file lock.


import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;

public class Example {
  public static void main(final String[] args) throws Exception {
    // Read from file
    final File inputFile = new File("src/main/resources/example.txt");
    try (final RandomAccessFile raf = new RandomAccessFile(inputFile, "rw")) {
      final FileChannel fc = raf.getChannel();
      final FileLock fl = fc.tryLock();
      if (fl == null) {
        // Failed to acquire lock
      } else {
        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final WritableByteChannel outChannel = Channels.newChannel(baos)) {
          for (final ByteBuffer buffer = ByteBuffer.allocate(1024); != -1;) {

          Files.write(Paths.get("target", "example.txt"), baos.toByteArray());
        } finally {

The above code can be downloaded from

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 award (Website).

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.