Java AsynchronousFileChannel with custom CompletionHandler

Description

Java AsynchronousFileChannel with custom CompletionHandler

import java.io.IOException;
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;

class MyClass {//from  w w w .  ja v a2  s.c  o m
  public Path path;
  public ByteBuffer buffer;
  public AsynchronousFileChannel asyncChannel;
}

class MyCompletionHandler implements CompletionHandler<Integer, MyClass> {
  @Override
  public void completed(Integer result, MyClass attach) {
    byte[] byteData = attach.buffer.array();
    Charset cs = Charset.forName("UTF-8");
    String data = new String(byteData, cs);
    System.out.println(data);

    try {
      // Close the channel
      attach.asyncChannel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void failed(Throwable e, MyClass attach) {
    System.out.format(e.getMessage());
    try {
      attach.asyncChannel.close();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
}

public class Main {

  public static void main(String[] args) {
    Path path = Paths.get("Main.txt");
    try {
      AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, 
          StandardOpenOption.READ);

      MyCompletionHandler handler = new MyCompletionHandler();
      // Get the data size in bytes to read
      int fileSize = (int) afc.size();
      ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);

      // Prepare the attachment
      MyClass attach = new MyClass();
      attach.asyncChannel = afc;
      attach.buffer = dataBuffer;
      attach.path = path;

      afc.read(dataBuffer, 0, attach, handler);

      try {
        System.out.println("Sleeping for 5 seconds...");
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      System.out.println("Done...");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related