The FileInputStream read method has the signature (is that the right term?) –
public int read(byte[] b) throws IOException
// Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.
// Returns: 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.
What is the advantage of having a signature like this over something like this –
public byte[] read(int numberOfBytes) throws IOException
// Reads up to numberOfBytes bytes of data from this input stream into an array of bytes.
// Returns- an array of bytes read. Array is empty if there is no more data because the end of the file has been reached.
The first form allows you to reuse the same
byte[]array for several executions. Basically you can read the whole stream producing minimal garbage (low GC activity).The latter is clearly more convenient but requires creating new instance of
byte[]every time it is executed internally withinread()method. This means that while reading 10 GiB file (even in 100-byte chunk) your application would allocate 10 GiB of memory in total – not at the same time, but still the garbage collector would work like crazy.Have a look at
Collection.toArray(T[])– it follows the same principle.