Example usage for java.nio.channels AsynchronousFileChannel open

List of usage examples for java.nio.channels AsynchronousFileChannel open

Introduction

In this page you can find the example usage for java.nio.channels AsynchronousFileChannel open.

Prototype

public static AsynchronousFileChannel open(Path file, Set<? extends OpenOption> options,
        ExecutorService executor, FileAttribute<?>... attrs) throws IOException 

Source Link

Document

Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("/asynchronous.txt"),
            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;//from  w w w .j av a 2  s. co  m
    result = writeFuture1.get();
    System.out.println("Sample write completed with " + result + " bytes written");
    result = writeFuture2.get();
    System.out.println("Box write completed with " + result + " bytes written");

}

From source file:Test.java

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/*w ww .j a  va2s  .co  m*/
        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);

}