Java FileChannel.tryLock()

Syntax

FileChannel.tryLock() has the following syntax.

public final FileLock tryLock()   throws IOException

Example

In the following code shows how to use FileChannel.tryLock() method.


import java.io.FileOutputStream;
import java.nio.channels.FileLock;
/*w w w. ja va  2s  . c om*/
public class Main {
  public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("file.txt");
    FileLock fl = fos.getChannel().tryLock();
    if (fl != null) {
      System.out.println("Locked File");
      Thread.sleep(100);
      fl.release();
      System.out.println("Released Lock");
    }
    fos.close();
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.nio.channels »




FileChannel