The documentation of read(byte[],int,int
says that it:
- Reads up to len bytes of data.
- An attempt is made to read as many as len bytes
- A smaller number may be read.
Since we are working with files that are right there in our hard disk, it seems reasonable to expect that the attempt will read the whole file, but input.read(result, 0, result.length)
is not guaranteed to read the whole file (it's not said anywhere in the documentation). Relying in undocumented behaviors is a source for bugs when the undocumented behavior change.
For instance, the file stream may be implemented differently in other JVMs, some OS may impose a limit on the number of bytes that you may read at once, the file may be located in the network, or you may later use that piece of code with another implementation of stream, which doesn't behave in that way.
Alternatively, if you are reading the whole file in an array, perhaps you could use DataInputStream.readFully
About the loop with read()
, it reads a single byte each time. That reduces performance if you are reading a big chunk of data, since each call to read()
will perform several tests (has the stream ended? etc) and may ask the OS for one byte. Since you already know that you want file.length()
bytes, there is no reason for not using the other more efficient forms.