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要高出不少。