Search code examples
javabytebuffernio

Difference between byte[] Files.readAllBytes(), and FileChannels.map (ByteBuffer/MappedByteBuffer)


I see all sort of benchmarkings and a direct/non-direct bytebuffer explanations on allocate, but I don't find a simple explanation on the difference when using bytes on memory on those methods.

Could somebody shed some light? It shooldn't be so difficult to tell what they do different.

Thanks!


Solution

  • readAllBytes copies the entire contents of a file into a new on-heap byte array, whereas mapping a file into a ByteBuffer permits access to the bytes of the file without loading it all into memory at once. You should expect some performance overhead to accessing bytes from the mapped byte buffer, but on the other hand you can map large files that would not fit into RAM otherwise.