mmap简单示例

Android Bind通信机制就是基于mmap实现的,可见其效率之高。

下面基于mmap来实现一个文件的保存:

JNI代码:

#include <jni.h>
#include <sys/mman.h>
#include <string>
#include <unistd.h>
#include <android/log.h>
#include <locale>
#include <fcntl.h>
#include <vector>

#define LOG_TAG "mmap_log"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)

extern "C"
jboolean
Java_com_caogd_test_MmapTest_write(JNIEnv *env, jobject clazz, jstring path, jstring text) {
    try {
        LOGI("1-write come in");
        std::string file_path = env->GetStringUTFChars(path, 0);
        std::string write_text = env->GetStringUTFChars(text, 0);
        unsigned int m_size = write_text.length();
        mode_t f_attrib = S_IRWXU | S_IRWXG | S_IRWXO;
        int fd = open(file_path.c_str(), O_RDWR | O_APPEND | O_CREAT, f_attrib);//打开文件
        LOGI("2-write m_size = %d\n", m_size);
        ftruncate(fd, m_size);//设置文件为一页大小
        int8_t *ptr = (int8_t *) mmap(0, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        memcpy(ptr, write_text.data(), m_size);
        close(fd);
        munmap((void *) ptr, m_size);
        LOGI("3-write fd = %d\n", fd);
        return true;
    } catch (...) {
        return false;
    }
}

Java层本地方法:

package com.caogd.test;

public class MmapTest {
    static {
        System.loadLibrary("mmapTest");
    }
    public static native boolean write(String path, String text);
}

使用方法:

String txt = "this is a mmap test";
MmapTest.write("/sdcard/test.txt",txt);

经测试,在大数据文本写入的时候,其效率比RandomAccessFile要高出不少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值