扩展Java内存映射字节缓冲区 [英] Expanding Java Memory-Mapped Byte Buffer

查看:213
本文介绍了扩展Java内存映射字节缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法扩展Java内存映射字节缓冲区,以便将新大小反映回磁盘上的映射文件?

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?

推荐答案

不,您需要调整底层文件的大小并重新创建Memory Mapped Byte Buffer。

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());

注意:设置文件长度有一些奇怪的行为。如果您通过地图在超出文件末尾的特定位置(使用map.position()或map.putX(position,...))写入文件,则值将附加到文件末尾该文件并没有写在你期望的位置(至少在linux上)。如果这是不受欢迎的行为,您需要将数据附加到文件中,以便真正增长文件。

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.

这篇关于扩展Java内存映射字节缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆