如何从FileChannel#transferFrom循环中断?

时间:2016-01-22 22:12:12

标签: 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;
}

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,则循环可以无限生存。

有没有可能的解决方案?

1 个答案:

答案 0 :(得分:3)

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