transferFrom和transferTo传输所有字节,如果使用FileChannel调用?

时间:2016-01-23 02:47:48

标签: java nio filechannel

一些互联网文档向我展示了示例,

FileChannel target;
FileChannel source;
target.trasferFrom(source, 0, source.size()); // done!

FileChannel source;
FileChannel target;
source.transferTo(0, source.size(), target); // done!

但文件说这些方法实际上可以转移少于给定的。

transferFromtransferTo如果sourcetargetFileChannel 的实例,请转移所有给定的计数?

我不应该像这样循环吗?

for (long count = Files.size(source); count > 0L;) {
    final long transferred = readable.transferTo(
        readable.position(), count, writable);
    readable.position(readable.position() + transferred);
    count -= transferred;
}

for (long count = Files.size(source); count > 0L;) {
    final long transferred = writable.transferFrom(
        readable, writable.position(), count);
    writable.position(writable.position() + transferred);
    count -= transferred;
}

1 个答案:

答案 0 :(得分:2)

是的,文档是正确的,你必须循环。