Write to a file with File Lock - Java File Path IO

Java examples for File Path IO:File Lock

Description

Write to a file with File Lock

Demo Code

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

public class Main {
  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.wrap("this is a test.".getBytes());
    Path path = Paths.get("C:/folder1/", "test.txt");
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, StandardOpenOption.WRITE)) {
      Future<FileLock> featureLock = asynchronousFileChannel.lock();
      System.out.println("Waiting for the file to be locked ...");
      FileLock lock = featureLock.get();
      // FileLock lock = asynchronousFileChannel.lock().get();
      if (lock.isValid()) {
        Future<Integer> featureWrite = asynchronousFileChannel.write(buffer, 0);
        System.out.println("Waiting for the bytes to be written ...");
        int written = featureWrite.get();
        //int written = asynchronousFileChannel.write(buffer,0).get();
        System.out.println(written + " -> "+ path.getFileName());
        lock.release();/*from ww w .j  a  v  a2 s . c o m*/
      }
    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials