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

问题描述

我一直在尝试编写一些非常快速的Java代码,它必须执行大量的I / O.我正在使用返回ByteBuffer的内存映射文件:

I've been trying to write some very fast Java code that has to do a lot of I/O. I'm using a memory mapped file that returns a ByteBuffer:

public static ByteBuffer byteBufferForFile(String fname){
    FileChannel vectorChannel;
    ByteBuffer vector;
    try {
        vectorChannel = new FileInputStream(fname).getChannel();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return null;
    }
    try {
        vector = vectorChannel.map(MapMode.READ_ONLY,0,vectorChannel.size());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return vector;
}

我遇到的问题是ByteBuffer .array()方法(应返回byte []数组)不适用于只读文件。我想编写我的代码,以便它可以使用内存中构造的内存缓冲区和从磁盘读取的缓冲区。但是我不想把我的所有缓冲区都包装成ByteBuffer.wrap()函数,因为我担心这会减慢速度。所以我一直在编写所有内容的两个版本,一个采用byte [],另一个采用ByteBuffer。

The problem that I'm having is that the ByteBuffer .array() method (which should return a byte[] array) doesn't work for read-only files. I want to write my code so that it will work with both memory buffers constructed in memory and buffers read from the disk. But I don't want to wrap all of my buffers a ByteBuffer.wrap() function because I'm worried that this will slow things down. So I've been writing two versions of everything, one that takes a byte[], the other that takes a ByteBuffer.

我应该包装所有内容吗?或者我应该双重写一切?

Should I just wrap everything? Or should I double-write everything?

推荐答案

是否有人确实检查过 ByteBuffers 由内存映射支持首先调用 .array(),无论readonly / readwrite如何?

Did anyone actually check to see if ByteBuffers created by memory mapping support invoking .array() in the first place, regardless of readonly/readwrite?

据我所知,据我所知,答案是 ByteBuffer 能够通过 ByteBuffer.array返回直接 byte [] 数组) ByteBuffer.hb byte [] )的存在而感到高兴,其中当创建 MappedByteBuffer 时,总是设置为null。

From my poking around, as far as I can tell, the answer is NO. A ByteBuffer's ability to return a direct byte[] array via ByteBuffer.array() is goverened by the presence of ByteBuffer.hb (byte[]), which is always set to null when a MappedByteBuffer is created.

对我来说哪种方式很糟糕,因为我希望做类似于作者想要做的事情。

Which kinda sucks for me, because I was hoping to do something similar to what the question author wanted to do.

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

09-18 05:48