Java FileChannel try to lock

Description

Java FileChannel try to lock


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 {
    RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
    FileChannel fileChannel = raf.getChannel();
    FileLock lock = fileChannel.tryLock();
    if (lock == null) {
      // Could not get the lock
    } else {/*from  w  ww  .  j  a  v a 2 s.  co  m*/
      // Got the lock
    }
    raf.close();
  }
}



PreviousNext

Related