Java AsynchronousFileChannel use Future object

Description

Java AsynchronousFileChannel use Future object

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

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

         Future<Integer> writeFuture1 = fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0);
         Future<Integer> writeFuture2 = fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0);

         int result;
         result = writeFuture1.get();/*from  w w  w . java 2  s. com*/
         System.out.println("Sample write completed with " + result + " bytes written");
         result = writeFuture2.get();
         System.out.println("Box write completed with " + result + " bytes written");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}



PreviousNext

Related