I understand how to create a memory mapped file, but my question is let's say that in the following line:
FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
ByteBuffer roBuf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, SIZE);
Where i set SIZE to be 2MB for example, does this means that it will only load 2MB of the file or will it read further in the file and update the buffer as i consume bytes from it?
The size of the buffer is the size you pass in. It will not grow or shrink.
The javadoc says:
EDIT:
Depending on what you mean by "updated with new data", the answer is yes.
So, other systems may do caching, but when those caches are flushed or otherwise up-to-date, they will agree with the view presented by the
FileChannel
.You can also use explicit calls to the
position
method and other methods to change what is presented by the view.It will only load the portion of the file specified in your buffer initialization. If you want it to read further you'll need to have some sort of read loop. While I would not go as far as saying this is tricky, if one isn't 100% familiar with the java.io and java.nio APIs involved then the chances of stuffing it up are high. (E.g.: not flipping the buffer; buffer/file edge case mistakes).
If you are looking for an easy approach to accessing this file in a ByteBuffer, consider using a
MappedByteBuffer
.The nice thing about a using an MBB in this context is that it won't necessarily actually load the entire buffer into memory, but rather only the parts you are accessing.