Example usage for java.nio.channels AsynchronousFileChannel write

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

Introduction

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

Prototype

public abstract <A> void write(ByteBuffer src, long position, A attachment,
        CompletionHandler<Integer, ? super A> handler);

Source Link

Document

Writes a sequence of bytes to this channel from the given buffer, starting at the given file position.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("test.txt");
    AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE,
            StandardOpenOption.CREATE);
    WriteHandler handler = new WriteHandler();
    ByteBuffer dataBuffer = getDataBuffer();
    Attachment attach = new Attachment();
    attach.asyncChannel = afc;//from  w  ww.  ja va  2  s .  c  om
    attach.buffer = dataBuffer;
    attach.path = path;

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

    System.out.println("Sleeping for 5  seconds...");
    Thread.sleep(5000);
}

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//from   w w  w . jav  a  2 s. 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);

}

From source file:ubicrypt.core.Utils.java

public static Observable<Long> write(final Path fullPath, final InputStream inputStream) {
    return Observable.create(subscriber -> {
        try {/*w  w  w. j  av  a 2  s.co  m*/
            final AtomicLong offset = new AtomicLong(0);
            final AsynchronousFileChannel afc = AsynchronousFileChannel.open(fullPath, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE);
            afc.lock(new Object(), new CompletionHandler<FileLock, Object>() {
                @Override
                public void completed(final FileLock lock, final Object attachment) {
                    //acquired lock
                    final byte[] buf = new byte[1 << 16];
                    try {
                        final int len = inputStream.read(buf);
                        if (len == -1) {
                            unsubscribe(subscriber, inputStream, lock);
                            return;
                        }
                        afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)), offset.get(), null,
                                new CompletionHandler<Integer, Object>() {
                                    @Override
                                    public void completed(final Integer result, final Object attachment) {
                                        //written chunk of bytes
                                        subscriber.onNext(offset.addAndGet(result));
                                        final byte[] buf = new byte[1 << 16];
                                        int len;
                                        try {
                                            len = inputStream.read(buf);
                                            if (len == -1) {
                                                unsubscribe(subscriber, inputStream, lock);
                                                log.debug("written:{}", fullPath);
                                                return;
                                            }
                                        } catch (final IOException e) {
                                            subscriber.onError(e);
                                            return;
                                        }
                                        if (len == -1) {
                                            unsubscribe(subscriber, inputStream, lock);
                                            log.debug("written:{}", fullPath);
                                            return;
                                        }
                                        afc.write(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, len)),
                                                offset.get(), null, this);
                                    }

                                    @Override
                                    public void failed(final Throwable exc, final Object attachment) {
                                        subscriber.onError(exc);
                                    }
                                });
                    } catch (final Exception e) {
                        close(inputStream, lock);
                        subscriber.onError(e);
                    }
                }

                @Override
                public void failed(final Throwable exc, final Object attachment) {
                    log.error("error on getting lock for:{}, error:{}", fullPath, exc.getMessage());
                    try {
                        inputStream.close();
                    } catch (final IOException e) {
                    }
                    subscriber.onError(exc);
                }
            });

        } catch (final Exception e) {
            log.error("error on file:{}", fullPath);
            subscriber.onError(e);
        }
    });
}