How to Lock a File

2 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.

package com.javacreed.examples.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.RandomAccessFile;
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); fc.read(buffer) != -1;) {
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
          }

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

The above code can be downloaded from https://github.com/javacreed/how-to-lock-a-file.git.

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 SearchSecurity.co.UK award (Website).

Leave a Comment