问题
I was looking at the definition of the read method of inputstream object, I am confused about how much data is read everytime since it says "reads some bytes"
public int read(byte[] b)
throws IOException
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.
Lets say i have a buffer array of size 200 and the data in the inputstream is 100 bytes. Is it guaranteed that inputStream.read gets all 100 bytes ?
回答1:
The whole point of this interface (or to be precise: abstract class): you can absolutely not rely on assuming how many bytes were read. You always always always have to check the return value of that method to know.
Background: there are many different implementations for this interface. Some my buffer, some may not. Some read "fixed" input (maybe from existing data in memory). Somebody might decide to give you a stream that turns to the internet, download a 10 GB file and then start sending you one byte after the other.
The only thing you know is: the method returns
the total number of bytes read into the buffer
End of story.
回答2:
InputStream is an abstract class (not an "object"). As such, it only specifies an interface, not an implementation, so implementation details depend on the actual nonabstract subclass you use.
回答3:
While nothing is guaranteed when reading from an InputStream
and concrete implementations (see the throws IOException
part), yes, if you have a buffer whose size is larger than the data read, all data should be read into the buffer, and the remaining byte
s in the buffer will not be written, hence staying at default primitive value of 0
.
This is also a caveat when piping from an InputStream
to, say, an OutputStream
.
The read
method returns the number of byte
s read or -1
when the stream ends.
This gives you an indication of how much of your buffer you need to write for an "exact copy".
Docs here.
回答4:
No. There's no guarentee. read(byte b[])
simply delegates to the read
method that takes three parameters read(byte b[], int off, int len) like so:
return read(b, 0, b.length);
The documentation for that method reads as follows:
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.
来源:https://stackoverflow.com/questions/45837998/how-much-data-does-inputstream-read-reads-in-java