Reputation: 22025
I'm writing a utility class for FileChannels.
Following method looks it may work.
// 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;
}
But the version for transferFrom
has problems.
// 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;
}
If src
reaches to an EOF before count, the loop may live infinitely.
Is there any possible solution for this?
Upvotes: 3
Views: 405
Reputation: 311052
This is an apparent deficiency in the API. There is no obvious mechanism to indicate end of stream. It appears that it can return zero at any time, not just at end of stream.
Upvotes: 5