介绍
ByteBuffer有三种类型
- No-Direct
- Direct
- MappedByteBuffer
其中Bytebuffer可以创建No-Direct和Direct类型,MappedByteBuffer类型是通过ByteBuffer的子类MappedByteBuffer来创建的。
今天简单介绍下MappedByteBuffer类。这个类对于读取文件来说非常高效。
MappedByteBuffer解读
例如,当我们多次读取一个文件内容时,可以加载文件内容到内存中,然后在内存中进行读取,而不需要从磁盘中读取了,减少了延迟时间。
但是当文件内容太大时,容易使内存溢出。我们可以使用MappedByteBuffer加载文件的部分内容来解决该问题。
读文件
public static void main(String[] args) throws Exception {
BasicOffHeapOperation basicOffHeapOperation = new BasicOffHeapOperation();
Path path = basicOffHeapOperation.getPathUriFromResource("fileToRead.txt");
CharBuffer charBuffer = null;
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel
.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
if (mappedByteBuffer != null) {
charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer);
}
}
System.out.println(charBuffer.toString());
}
private Path getPathUriFromResource(String fileName) throws URISyntaxException {
ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).toURI());
}
输出如下:
i need confident for myself,
i need work hard!
i love my wife. i love my daughter
写文件
通过MappedByteBuffer写内容到文件中。
public static void main(String[] args) throws URISyntaxException, IOException {
BasicOffHeap basicOffHeap = new BasicOffHeap();
CharBuffer charBuffer = CharBuffer.wrap("this will be written to the file\nhello world");
Path path = basicOffHeap.getUriFromResource("fileToWrite.txt");
System.out.println(path.toString());
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(path, EnumSet.of(
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING
))) {
MappedByteBuffer mappedByteBuffer = fileChannel
.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) {
mappedByteBuffer.put(Charset.forName("UTF-8").encode(charBuffer));
}
}
}
private Path getUriFromResource(String fileName) throws URISyntaxException {
ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).toURI());
}