Java AsynchronousFileChannel create for read and write

Description

Java AsynchronousFileChannel create for read and write


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Main {
  public static void main(String[] args) {
    Path path = Paths.get("Main.txt");

    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path,
        StandardOpenOption.WRITE,
        StandardOpenOption.CREATE)) {

      ByteBuffer dataBuffer = ByteBuffer.wrap(new byte[] {63,64,65,66});

      // Perform the asynchronous write operation
      Future<Integer> result = afc.write(dataBuffer, 0);

      while (!result.isDone()) {
        try {//from w w  w .j  a va  2s  .c  o m
          System.out.println("Sleeping for 2 seconds...");
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      try {
        int writtenBytes = result.get();
        System.out.format("%s bytes written to %s%n", writtenBytes,
            path.toAbsolutePath());
      } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related