javaioinputstreamfileinputstreamstandard-library

Does FileInputStream incorrectly implement InputStream?


The docs for InputStream.read(bytes) say "This method blocks until input data is available, end of file is detected, or an exception is thrown."

However, java.io.FileInputStream extends java.io.InputStream and the docs for FileInputStream.read(bytes) state no such guarantee:

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

In practice, FileInputStream can indeed return before all the input is available, so it seems both the docs and the implementation do not follow the contract of InputStream.

Is this a bug? Is it a known bug?

UPDATE: to clarify: System.in is a FileInputStream. I am seeing System.in.read(buf) return a nonzero int that is neither all of the bytes, nor -1. If I use System.in.readNBytes(buf, 0, theNumberOfBytesIAmExpecting) then I get all the bytes the sender is sending.


Solution

  • I think that the situation is more subtle, - InputStream.read(byte[] b) just delegates to InputStream.read(byte[] b, int off, int len)

    And for read(byte[] b, int off, int len) it seems that the contract/promise broken (or at least different).

    For InputStream.read(byte[] b, int off, int len) the documentation states:

    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.

    (and it is implemented this way: - the requested amount of data is always read)

    For FileInputStream.read(byte[] b, int off, int len) - there is no such promise (and implementation may not read all the requested amount).

    Many other high-level methods delegate to read(byte[] b, int off, int len) and I would consider that at least for this method the promise of InputStream (to read either the requested amount or till the end of the steam) is broken in FileInputStream and it creates confusion.