Memory mapped file java NIO

前端 未结 2 1206
失恋的感觉
失恋的感觉 2021-01-07 01:07

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,         


        
2条回答
  •  旧时难觅i
    2021-01-07 01:42

    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?

    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.

    RandomAccessFile raf = new RandomAccessFile(file, "r");
    FileChannel fc = raf.getChannel();
    MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    

    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.

提交回复
热议问题