Java FileChannel lock file

Description

Java FileChannel lock file

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

public class Main {
  public static void main(String[] args) throws Exception {
    // Create a random access file and obtain a channel for it
    RandomAccessFile raf = new RandomAccessFile("Main.java", "rw");
    FileChannel fileChannel = raf.getChannel();

    // Get an exclusive lock on the file
    FileLock lock = fileChannel.lock();
    if (lock == null) {
      // Could not get the lock
    } else {//from w w  w.j av  a2s .  com
      // Got the lock
    }

    raf.close();
  }
}



PreviousNext

Related