Locking a Channel's File - Java File Path IO

Java examples for File Path IO:File Channel

Description

Locking a Channel's File

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class Main {
  public static void main(String[] args) throws Exception{
    Path path = Paths.get("C:/folder1/email", "test.txt");
    ByteBuffer buffer = ByteBuffer.wrap("test test".getBytes());
    try (FileChannel fileChannel = (FileChannel.open(path,
        EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {
      FileLock lock = fileChannel.lock();
      lock = fileChannel.tryLock();// ww  w  . j  av a 2s  .co m
      if (lock.isValid()) {
        System.out.println("Writing to a locked file ...");
        Thread.sleep(60000);
        fileChannel.position(0);
        fileChannel.write(buffer);
          Thread.sleep(60000);
      }
      lock.release();
      System.out.println("\nLock released!");
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials