内存映射Java中的大文件

问题描述 投票:8回答:2

是否可以在Java中对大型文件(多个GB)进行内存映射?

这种FileChannel方法看起来很有希望:

MappedByteBuffer map(FileChannel.MapMode mode, long position, long size)

positionsize都允许64位值 - 到目前为止,非常好。

然而,MappedByteBuffer只提供32位位置的方法(get(int index)position(int newPosition)等),这似乎意味着我无法映射大于2 GB的文件。

我怎样才能解决这个限制?

java nio memory-mapped-files
2个回答
7
投票

看看Using a memory mapped file for a huge matrix代码,它显示了如何创建MappedByteBuffer列表,每个小于2 GB,以映射整个文件:

private static final int MAPPING_SIZE = 1 << 30;
...
long size = 8L * width * height;
for (long offset = 0; offset < size; offset += MAPPING_SIZE) {
    long size2 = Math.min(size - offset, MAPPING_SIZE);
    mappings.add(raf.getChannel().map(FileChannel.MapMode.READ_WRITE, offset, size2));
}

根据JDK-6347833 (fs) Enhance MappedByteBuffer to support sizes >2GB on 64 bit platforms,2 GB限制的原因是:

MappedByteBuffer是一个ByteBuffer,具有支持内存映射文件区域的附加操作。要支持映射大于Integer.MAX_VALUE的区域,需要并行的类层次结构。目前唯一的解决方案是创建多个MappedByteBuffers,其中每个都对应一个不大于2GB的区域。


3
投票

如前所述,由于使用了整数索引/位置指针,MappedByteBuffer具有2GB的限制。

为了解决这个问题,你可以使用像larray这样的替代实现

© www.soinside.com 2019 - 2024. All rights reserved.