Expanding Java Memory-Mapped Byte Buffer

£可爱£侵袭症+ 提交于 2019-12-20 12:28:40

问题


Is there a way to expand the Java memory-mapped byte buffer such that the new size is reflected back to the mapped file on disk?


回答1:


No, you will need to adjust the size of the underlying file and recreate the Memory Mapped Byte Buffer.

RandomAccessFile file = new RandomAccessFile(/* some file */);
MappedByteBuffer buffer = file.getChannel().map(MapMode.READ_WRITE, 0, file.length());

// Some stuff happens...

// adjust the size
file.setLength(newLength);

// recreate the memory mapped buffer
buffer = file.getChannel().map(MapMode.READ_WRITE, 0, file.length());

Note: Setting the file length has some slightly odd behaviour. If you write to the file via the map at a specific position that is beyond the end of the file (either using map.position() or map.putX(position, ...)) the values will be appended to the end of the file and not written at the position you expect (on linux at least). If this is undesired behaviour you will need to append data to the file in order to truly grow the file.



来源:https://stackoverflow.com/questions/3028522/expanding-java-memory-mapped-byte-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!