1

我尝试使用 AsynchronousFileChannel 来实现复制文件。用于读写的 AsynchronousFileChannel 对象声明为

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

读取的 CompletionHandler 看起来像

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 ...");
        }
    };

然后我开始读取文件

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

问题是,读取完成后,如果我写文件(请参阅注释“问题行”以查看它的调用位置)

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

不会写出任何内容。我必须再次包装缓冲区

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

为了看到写出的内容

我的问题是,我必须使用 ByteBuffer 来包装另一个 ByteBuffer 的内容的原因是什么?

4

1 回答 1

3

我必须使用 ByteBuffer 来包装另一个 ByteBuffer 的内容的原因是什么?

你没有。你应该把原件翻过来ByteBuffer。通过调用 可以得到类似的效果wrap(),它将position新包装ByteBuffer的 设置为零。

于 2014-11-10T02:50:04.003 回答