Writing to a file using the AsynchronousFileChannel class - Java Network

Java examples for Network:Asynchronous Server

Description

Writing to a file using the AsynchronousFileChannel class

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.WritePendingException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class Main {

    public static void main(String[] args) {
        try (AsynchronousFileChannel fileChannel =
                        AsynchronousFileChannel.open(Paths.get("/home/docs/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());
                        }/*w w w . j a  v a  2s  . co  m*/

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


        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (WritePendingException ex) {
            ex.printStackTrace();
        }
    }
}

Related Tutorials