FileInputStream 是否错误地实现了 InputStream?

Does FileInputStream incorrectly implement InputStream?

The docs for InputStream.read(bytes) 说“此方法会阻塞,直到输入数据可用、检测到文件结尾或引发异常。”

但是,java.io.FileInputStream 扩展了 java.io.InputStream the docs for FileInputStream.read(bytes) 声明没有这样的保证:

 * Reads up to {@code b.length} bytes of data from this input
 * stream into an array of bytes. This method blocks until some input
 * is available.

实际上,FileInputStream确实可以在所有输入可用之前return,所以文档和实现似乎都没有遵循InputStream的约定。

这是一个错误吗?这是一个已知错误吗?

更新:澄清:System.inFileInputStream。我看到 System.in.read(buf) return 一个非零整数 既不是 所有字节, 也不是 -1 .如果我使用 System.in.readNBytes(buf, 0, theNumberOfBytesIAmExpecting) 那么我会得到发件人发送的所有字节。

这不是违反合同,因此不是错误。

InputStream 的文档指定它阻塞直到“输入数据可用”,这与“所有输入都可用”不同。

如果您指的是“文件结尾”方面,请继续阅读 FileInputStream.read 的 Javadoc,其中指定

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

我认为情况比较微妙,- InputStream.read(byte[] b) 只是委托给 InputStream.read(byte[] b, int off, int len)

read(byte[] b, int off, int len) 似乎 contract/promise 损坏(或至少不同)。

对于 InputStream.read(byte[] b, int off, int len),文档指出:

The default implementation of this method blocks until the requested amount of input data len has been read, end of file is detected, or an exception is thrown. Subclasses are encouraged to provide a more efficient implementation of this method.

(并且是这样实现的:- 总是读取请求的数据量)

对于 FileInputStream.read(byte[] b, int off, int len) - 没有这样的承诺(并且实施可能不会读取所有请求的数量)。

许多其他 high-level 方法委托给 read(byte[] b, int off, int len) 我认为至少对于此方法 InputStream 的承诺(读取请求的数量或直到结束蒸汽)在 FileInputStream 中损坏,造成混乱。