Home > database >  Does FileInputStream incorrectly implement InputStream?
Does FileInputStream incorrectly implement InputStream?

Time:02-12

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.

CodePudding user response:

It is not a contract violation, and is therefore not a bug.

The doc for InputStream specifies that it blocks until "input data is available," which is not the same thing as "all the input is available."

If you're referring to the "end of file" aspect, continue to read the Javadoc for FileInputStream.read, which specifies

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.

  • Related