Java 无法使用MappedByteBuffer读取块中的文件
在读操作期间,我得到java.io.IOException:通道未打开以进行写入-无法将文件扩展到所需大小 我编写了一个简单的程序,用MappedByteBuffer读取文件。其思想是根据API读取带有区域的文件。但在执行过程中,我遇到了异常。我有一个包含以下内容的测试文件: SimpleTestFileJava 无法使用MappedByteBuffer读取块中的文件,java,ioexception,filechannel,mappedbytebuffer,Java,Ioexception,Filechannel,Mappedbytebuffer,在读操作期间,我得到java.io.IOException:通道未打开以进行写入-无法将文件扩展到所需大小 我编写了一个简单的程序,用MappedByteBuffer读取文件。其思想是根据API读取带有区域的文件。但在执行过程中,我遇到了异常。我有一个包含以下内容的测试文件: SimpleTestFile static void readFileWithChunks(final String file){ final Path pathToFile = Paths.get(file);
static void readFileWithChunks(final String file){
final Path pathToFile = Paths.get(file);
LOG.info("Path to file: {}", pathToFile.toString());
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToFile, EnumSet.of(StandardOpenOption.READ))) {
final long fileSize = fileChannel.size();
LOG.info("Total size of the file: {} bytes", fileSize);
final int maxChunkSize = 4;
long startPosition = 0;
long endPosition = 0;
// main cycle to read chunks of data from file
while (startPosition < fileSize){
if (endPosition + maxChunkSize < fileSize){
endPosition += maxChunkSize;
} else {
endPosition = fileSize;
}
readChunk(fileChannel, startPosition, endPosition);
startPosition = endPosition;
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void readChunk(final FileChannel fileChannel, final long startPosition, final long endPosition) throws IOException {
LOG.info("Start position: {}; End position: {}", startPosition, endPosition);
final MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startPosition, endPosition);
final int bufferSize = (int) (endPosition - startPosition);
LOG.info("Buffer size: {}", bufferSize);
final byte[] buffer = new byte[bufferSize];
mappedByteBuffer.get(buffer);
LOG.info("Content of the buffer: {}", new String(buffer, StandardCharsets.UTF_8));
}
这是你的问题:
final MappedByteBuffer mappedByteBuffer =
fileChannel.map(
FileChannel.MapMode.READ_ONLY,
startPosition,
endPosition // <-- (endPosition - startPosition)
);
当您将映射视图推进到文件长度之外时,基础文件将被扩展以容纳(在文件的前一端和新一端之间具有未定义的内容)。扩展文件需要写访问权限,因此会出现异常。这是您的问题:
final MappedByteBuffer mappedByteBuffer =
fileChannel.map(
FileChannel.MapMode.READ_ONLY,
startPosition,
endPosition // <-- (endPosition - startPosition)
);
当您将映射视图推进到文件长度之外时,基础文件将被扩展以容纳(在文件的前一端和新一端之间具有未定义的内容)。扩展文件需要写访问权限,因此出现异常。问题仍然没有解决方案。如果我改为写模式,它会向文件中添加尾随零。这个问题仍然没有解决方案。如果我改为写模式,它会向文件中添加尾随零。
public abstract MappedByteBuffer map(MapMode mode,
long position, long size)
throws IOException;