The answer to the question in your title is 'no'. It's only obliged by contract to transfer at least one byte. If you want more you have to loop until you get them.
Does FileChannel.read(ByteBuffer) work like RandomAccessFile.readFully(byte[])?
Question
RandomAccessFile.readFully docs say
"This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown."
I'd like similar behavior from FileChannel.read but not sure the right way to guarantee it.
Solution
OTHER TIPS
I can't find an existing utility method so here is a not-well-tested implementation
void readFully(FileChannel file, ByteBuffer buf) throws IOException {
int n = buf.remaining();
int toRead = n;
while (n > 0) {
int amt = file.read(buf);
if (amt == -1) {
int read = toRead - n;
throw new EOFException("reached end of stream after reading "
+ read + " bytes; " + toRead + " bytes expected");
} else {
n -= amt;
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow