Does FileChannel.read(ByteBuffer) work like RandomAccessFile.readFully(byte[])?

StackOverflow https://stackoverflow.com/questions/22214477

  •  10-06-2023
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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;
            }
        }
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top