我怎样才能打破 FileChannel#transferFrom 循环?
How can I break from a FileChannel#transferFrom loop?
我正在为 FileChannel 编写实用程序 class。
下面的方法看起来可行。
// 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 中明显的缺陷。没有明显的机制来指示流结束。它似乎可以 return 随时归零,而不仅仅是在流的末尾。
我正在为 FileChannel 编写实用程序 class。
下面的方法看起来可行。
// 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 中明显的缺陷。没有明显的机制来指示流结束。它似乎可以 return 随时归零,而不仅仅是在流的末尾。