MappedByteBuffer

介绍

ByteBuffer有三种类型

  1. No-Direct
  2. Direct
  3. 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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值