Question

I was reading the book and it has got the below lines:

A MemoryMappedBuffer directly reflects the disk file with which it is associated. If the file is structurally modified while the mapping is in effect, strange behavior can result (exact behaviors are, of course, operating system- and filesystem-dependent). A MemoryMappedBuffer has a fixed size, but the file it's mapped to is elastic. Specifically, if a file's size changes while the mapping is in effect, some or all of the buffer may become inaccessible, undefined data could be returned, or unchecked exceptions could be thrown.

So my questions are:

  • Can't i append text to the files which i have already mapped. If yes then how?
  • Can somebody please guide me what are the real use cases of memory mapped file and would be great if you can mention what specific problem you have solved by this.

Please bear with me if the questions are pretty naive. Thanks.

Was it helpful?

Solution

Memory mapped files are much faster then regular ByteBuffer version but it will allocate whole memory for example if you map 4MB file operating system will create 4MB file on filesystem that map file to a memory and you can directly write to file just by writing to memory. This is handy when you know exactly how much of data you want to write as if you write less then specified rest of the data array will be filled with zeros. Also Windows will lock the file (can't be deleted until JVM exits), this is not the case on Linux.

Below is the example of appending to a file with memory mapped buffer, for position just put the file size of file that you are writing to:

int BUFFER_SIZE = 4 * 1024 * 1024; // 4MB
String mainPath = "C:\\temp.txt";
SeekableByteChannel dataFileChannel = Files.newByteChannel("C:\\temp.txt", EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.APPEND));
MappedByteBuffer writeBuffer = dataFileChannel.map(FileChannel.MapMode.READ_WRITE, FILE_SIZE, BUFFER_SIZE);
writeBuffer.write(arrayOfBytes);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top