Writing to a file using the AsynchronousFileChannel class : Asynchronous Channel « JDK 7 « Java






Writing to a file using the AsynchronousFileChannel class



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 Test {

  public static void main(String[] args) throws Exception {
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(
        Paths.get("/asynchronous.txt"), StandardOpenOption.READ,
        StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {

      @Override
      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);

  }
}

 








Related examples in the same category

1.Using AsynchronousFileChannel and Future to read
2.Using AsynchronousFileChannel and CompletionHandler to read a file
3.Using AsynchronousFileChannel to write ByteBuffer and return Future
4.Reading from a file using the AsynchronousFileChannel class
5.Reading from a file using the AsynchronousFileChannel class
6.Managing asynchronous communication using the AsynchronousServerSocketChannel
7.Communication with AsynchronousSocketChannel