有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不支持文件通道。read(ByteBuffer)的工作方式与RandomAccessFile类似。准备就绪(字节[])?

随机存取文件。准备好了的医生说

"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."

我希望FileChannel有类似的行为。阅读,但不确定正确的方法来保证它


共 (2) 个答案

  1. # 1 楼答案

    我找不到现有的实用工具方法,因此这里是一个未经良好测试的实现

        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;
                }
            }
        }
    
  2. # 2 楼答案

    你标题中的问题的答案是“否”。根据合同,它必须至少传输一个字节。如果你想要更多,你必须循环直到你得到它们