下面是我写的代码.我想做一件简单的事情,将二进制文件数据存储到byteBuffer中.
File file = new File(fileName);
try {
ReadableByteChannel channel = new FileInputStream(fileName).getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(file.length());
// How can use buf.read to get all the contents?
} catch (Exception e){
}
Run Code Online (Sandbox Code Playgroud)
我在想
read从通道获取所有数据并将其存储在ByteBuffer中ByteBuffer,除了使用Fileobject来获取文件的长度我更喜欢使用内存映射.
FileChannel channel = new FileInputStream(fileName).getChannel();
ByteBuffer buf = channel.map(MapMode.READ_ONLY,0,channel.size());
Run Code Online (Sandbox Code Playgroud)
如果文件大于2 GB,则必须具有多个映射.从正面来看,无论大小如何,这都需要大约10毫秒,并且不管文件的大小如何都不会使用太多堆或直接内存.
来自ReadableByteChannel Javadocs
read(ByteBuffer dst)
尝试从通道读取最多 r 个字节,其中 r 是调用此方法时缓冲区中剩余的字节数,即 dst.remaining()。
所以 ...channel.read(buf);
至于你的第二个问题,如果你想立即将文件的全部内容读入内存,这似乎是一个合理的方法。
| 归档时间: |
|
| 查看次数: |
7396 次 |
| 最近记录: |