gpt4 book ai didi

java - 我怎样才能打破 FileChannel#transferFrom 循环?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:07:07 26 4
gpt4 key购买 nike

我正在为 FileChannel 编写实用程序类

以下方法看起来可能有效。

// tries to transfer as many bytes as specified
public static long transferTo(final FileChannel src, long position,
long count, final WritableByteChannel dst)
throws IOException {

long accumulated = 0L;

while (position < src.size()) {
final long transferred = src.transferTo(position, count, dst);
position += transferred;
count -= transferred;
accumulated += transferred;
}

return accumulated;
}

但是 transferFrom 的版本有问题。

// tries to transfer as many bytes as specified
public static long transferFrom(final FileChannel dst,
final ReadableByteChannel src,
long position, long count)
throws IOException {

long accumulated = 0L;

dst.position(position + count); // extend the position for writing
while (count > 0L) {
final long transferred = dst.transferFrom(src, position, count);
position += transferred;
count -= transferred;
// not gonna break if src is shorter than count
}

return accumulated;
}

如果 src 在计数之前到达 EOF,则循环可能无限存在。

有什么可能的解决方案吗?

最佳答案

这是 API 中的明显缺陷。没有明显的机制来指示流结束。它似乎可以随时返回零,而不仅仅是在流的末尾。

关于java - 我怎样才能打破 FileChannel#transferFrom 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com