This library aims to bring memory mapped files to java. The goal is to give better control over the creation, modification and destruction in contrast to already present MappedByteBuffer. It tries to unify the interface for using such maps on different operating systems which means that a lot of details are not possible to implement. Furthermore, there might be some cases where you might need to do tedious work that may not be required on your target platform.
This library supports windows and linux.
For each file you need to create a new MemoryMap object and give it a path to a file:
MemoryMap mm = MemoryMapFactory.getInstance(); mm.openFile("./test.txt");
At least on windows you need to open a mapping with the estimated filesize:
Now we are done with our preparation and we can start with mapping parts of the file (called a view) to the memory. The memory is presented as a simple buffer where you can read and write from. The first argument is the offset from the beginning of the file and the second one is the size you want to be able to access.
ByteBuf b = mm.mapView(20, 10);
In this example we write the string "Hello" at position 20 in the file.
Of course you can overwrite already written content easily:
Or if you prefer the direct way:
We can also read from the map:
byte bytes = new byte; b.getBytes(0, bytes); System.out.println(new String(bytes, CharsetUtil.UTF_8));
When the work of this buffer is done we need to release it:
When we are done with all file operations we need to truncate the file to the expected size and close it: