Java AsynchronousFileChannel write to file

Description

Java AsynchronousFileChannel write to file

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  v  a2s  . co  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();
    }
  }
}
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Main {
   public static void main(String[] args) {
      try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("Main.java"),
            StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
         CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {

            @Override/*from  w  ww . j a va 2s.  co  m*/
            public void completed(Integer result, Object attachment) {
               System.out.println("Attachment: " + attachment + " " + result + " bytes written");
               System.out.println("CompletionHandler Thread ID: " + Thread.currentThread().getId());
            }

            @Override
            public void failed(Throwable e, Object attachment) {
               System.err.println("Attachment: " + attachment + " failed with:");
               e.printStackTrace();
            }
         };

         System.out.println("Main Thread ID: " + Thread.currentThread().getId());
         fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0, "First Write", handler);
         fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0, "Second Write", handler);

      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}



PreviousNext

Related