设置和问题
- 我正在将一个文件转换为一个新文件,但不知道输出缓冲区应该有多大
- 加密、编码、压缩等都具有这个特性
- 如果输出
MappedByteBuffer
太小,将会抛出java.nio.BufferOverflowException
如果输出
MappedByteBuffer
太大,生成的文件将有尾随零如何自动增长
MappedByteBuffer
或截掉尾随零?
一个小例子
FileChannel inChan = FileChannel.open(Paths.get(inString), StandardOpenOption.READ);
FileChannel outChan = FileChannel.open(Paths.get(outString), StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
MappedByteBuffer inMBB = inChan.map(MapMode.READ_ONLY, 0, inChan.size());
// The following will buffer overflow after the call to transform
MappedByteBuffer outMBB = outChan.map(MapMode.READ_WRITE, 0, 0);
// This will have trailing zeros after the call to transform
MappedByteBuffer outMBB = outChan.map(MapMode.READ_WRITE, 0, inChan.size() + 1024);
transform(inMBB, outMBB);
最佳答案
要创建不同大小的映射,您需要创建新的内存映射。这意味着要么创建更多映射并将它们拼接在一起,要么创建一个新的更大映射,请注意 ByteBuffer 仅限于 Integer.MAX_VALUE 大小。
我们开发了一个库MappedBytes
,它可以按需增长(以您定义的 block 大小),并且您可以在知道文件长度后截断文件长度。
例如
Bytes bytes = MappedBytes.mappedFile(filename, 64 << 20); // 64 MB
注意:Bytes 内置了对大于 2 GB 的 block /文件、加密和压缩的支持,这可能很有用。
关于java - 如何有效地使用目标 MappedByteBuffer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42946012/