File Read and CompletionHandler with AsynchronousFileChannel - Java File Path IO

Java examples for File Path IO:File Channel

Description

File Read and CompletionHandler with AsynchronousFileChannel

Demo Code

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Main {
  static Thread current;

  public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.allocate(100);
    Path path = Paths.get("C:/folder1/", "test.txt");
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, StandardOpenOption.READ)) {
      current = Thread.currentThread();
      asynchronousFileChannel.read(buffer, 0, "Read operation status ...",
          new CompletionHandler<Integer, Object>() {
            @Override/*from w  w w  .  j a  va 2 s. c  o m*/
            public void completed(Integer result, Object attachment) {
              System.out.println(attachment);
              System.out.print("Read bytes: " + result);
              current.interrupt();
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
              System.out.println(attachment);
              System.out.println("Error:" + exc);
              current.interrupt();
            }
          });

      System.out.println("waiting ...\n");
      try {
        current.join();
      } catch (InterruptedException e) {
      }
      System.out.println("done.");
    } catch (Exception ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials