如何打破 FileChannel#transferFrom 循环?

Jin*_*won 3 java nio filechannel

我正在为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;
}
Run Code Online (Sandbox Code Playgroud)

但是版本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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

use*_*421 5

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