Search code examples
javabytebufferjava.nio.file

Java AsynchronousFileChannel and ByteBuffer


I try to use AsynchronousFileChannel to implement copying file. The AsynchronousFileChannel objects for read and write are declare as

AsynchronousFileChannel asyncRead = AsynchronousFileChannel.open(sourcePath);
AsynchronousFileChannel asyncWrite = AsynchronousFileChannel.open(targetPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

The CompletionHandler for read looks like

CompletionHandler<Integer, ByteBuffer> handlerRead = new CompletionHandler<Integer, ByteBuffer>() {

        @Override
        public void completed(Integer arg0, ByteBuffer arg1) {
            System.out.println("finished read ...");

            // question line
            asyncWrite.write(ByteBuffer.wrap(arg1.array()), 0, null, handlerWrite);
        }

        @Override
        public void failed(Throwable arg0, ByteBuffer arg1) {
            System.out.println("failed to read ...");
        }
    };

Then I start file read by

asyncRead.read(buffer, 0, buffer, handlerRead);

The question is, after the read is complete, If I write file (please see the the comment "question line" to see where it is called)

// no output
asyncWrite.write(arg1, 0, null, handlerWrite);

there will be no content written out. I have to wrap the buffer again

// works fine
asyncWrite.write(ByteBuffer.wrap(arg1.array()), 0, null, handlerWrite);

in order to see the content written out

My question is, what is the reason I have to use the ByteBuffer to wrap the content of another ByteBuffer?


Solution

  • what is the reason I have to use the ByteBuffer to wrap the content of another ByteBuffer?

    You don't. You should have flipped the original ByteBuffer instead. You got a similar effect by calling wrap(), which sets the position of the newly wrapped ByteBuffer to zero.