Creating a File Lock on a File - Java File Path IO

Java examples for File Path IO:File Lock

Description

Creating a File Lock on a File

Demo Code

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Main {

  public void main(String[] argv) {
    try {/*from w  w w .  j  ava  2  s . c o  m*/
      File file = new File("filename");
      FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

      // Use the file channel to create a lock on the file.
      // blocks until it can retrieve the lock.
      FileLock lock = channel.lock();

      // Try acquiring the lock without blocking. returns
      // null or throws an exception if the file is already locked.
      try {
        lock = channel.tryLock();
      } catch (OverlappingFileLockException e) {
        // File is already locked in this thread or virtual machine
      }

      lock.release();

      channel.close();
    } catch (Exception e) {
    }
  }
}

Related Tutorials