我一直在尝试编写一些非常快速的Java代码,需要进行大量的I/O操作。我使用了返回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
。我应该只是包装所有东西吗?还是应该把所有东西都写两遍?