Decode and display the content of the destination ByteBuffer into the completed() method of CompletionHandler - Java File Path IO

Java examples for File Path IO:ByteBuffer

Description

Decode and display the content of the destination ByteBuffer into the completed() method of CompletionHandler

Demo Code

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

public class Main {
  static Thread current;
  static final Path path = Paths.get("C:/folder1/", "test.txt");
  public static void main(String[] args) {
    CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
      String encoding = System.getProperty("file.encoding");
      @Override/*from www . java 2  s  . co  m*/
      public void completed(Integer result, ByteBuffer attachment) {
        System.out.println("Read bytes: " + result);
        attachment.flip();
        System.out.print(Charset.forName(encoding).decode(attachment));
        attachment.clear();
        current.interrupt();
      }
      @Override
      public void failed(Throwable exc, ByteBuffer attachment) {
        System.out.println(attachment);
        System.out.println("Error:" + exc);
        current.interrupt();
      }
    };
    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
        .open(path, StandardOpenOption.READ)) {
      current = Thread.currentThread();
      ByteBuffer buffer = ByteBuffer.allocate(100);
      asynchronousFileChannel.read(buffer, 0, buffer, handler);
      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