内存映射文件java NIO [英] Memory mapped file java NIO

查看:103
本文介绍了内存映射文件java NIO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解如何创建内存映射文件,但我的问题是在下面的行中说:

I understand how to create a memory mapped file, but my question is let's say that in the following line:

FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
ByteBuffer roBuf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, SIZE);

例如,我将SIZE设置为2MB,这是否意味着它只会加载2MB的文件还是会在文件中进一步读取并更新缓冲区,因为我从中消耗了字节?

Where i set SIZE to be 2MB for example, does this means that it will only load 2MB of the file or will it read further in the file and update the buffer as i consume bytes from it?

推荐答案


<例如,我将SIZE设置为2MB,这是否意味着它只会加载2MB的文件,还是会在文件中进一步读取并更新缓冲区,因为我从中消耗了字节?

Where i set SIZE to be 2MB for example, does this means that it will only load 2MB of the file or will it read further in the file and update the buffer as i consume bytes from it?

它只会加载缓冲区初始化中指定的文件部分。如果你想进一步阅读,你需要有一些读取循环。虽然我不会说这很棘手,如果一个人不熟悉所涉及的java.io和java.nio API,那么填充它的可能性很高。 (例如:不翻转缓冲区;缓冲区/文件边缘错误)。

It will only load the portion of the file specified in your buffer initialization. If you want it to read further you'll need to have some sort of read loop. While I would not go as far as saying this is tricky, if one isn't 100% familiar with the java.io and java.nio APIs involved then the chances of stuffing it up are high. (E.g.: not flipping the buffer; buffer/file edge case mistakes).

如果您正在寻找一种在ByteBuffer中访问此文件的简单方法,请考虑使用 MappedByteBuffer

If you are looking for an easy approach to accessing this file in a ByteBuffer, consider using a MappedByteBuffer.

RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel fc = raf.getChannel();
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

在这种情况下使用MBB的好处是它不一定会实际加载整个缓冲区到内存中,而只是你正在访问的部分。

The nice thing about a using an MBB in this context is that it won't necessarily actually load the entire buffer into memory, but rather only the parts you are accessing.

这篇关于内存映射文件java NIO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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