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