要模仿的java方法如下:
private static MappedByteBuffer loadModelFile()
throws IOException {
@SuppressLint("SdCardPath") File file = new File("/sdcard/libs/data.txt");
FileInputStream inputStream = new FileInputStream(file);
FileChannel fileChannel = inputStream.getChannel();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}
里面的MapMode是FileChannel的内部类
jobject get_byte_buffer(JNIEnv *pEnv) {
//new file
jclass jc_file = pEnv->FindClass("java/io/File");
jmethodID file_init = pEnv->GetMethodID(jc_file, "<init>", "(Ljava/lang/String;)V");
jobject file = pEnv->NewObject(jc_file, file_init, pEnv->NewStringUTF("/sdcard/libs/data.txt"));
//new FileInputStream
jclass jc_fileInputStream = pEnv->FindClass("java/io/FileInputStream");
jmethodID fileInputStream_init = pEnv->GetMethodID(jc_fileInputStream, "<init>", "(Ljava/io/File;)V");
jobject fileInputStream = pEnv->NewObject(jc_fileInputStream, fileInputStream_init, file);
// get FileChannel
jmethodID jm_getChannel = pEnv->GetMethodID(jc_fileInputStream, "getChannel", "()Ljava/nio/channels/FileChannel;");
jobject fileChannel = pEnv->CallObjectMethod(fileInputStream, jm_getChannel);
//read_only 马丹谷歌,这样是对的你报鸡巴错
jclass jc_read_only = pEnv->FindClass("java/nio/channels/FileChannel$MapMode");
jfieldID jf_read_only = pEnv->GetStaticFieldID(jc_read_only, "READ_ONLY", "Ljava/nio/channels/FileChannel$MapMode;");
jobject read_only = pEnv->GetStaticObjectField(jc_read_only, jf_read_only);
//file length
jmethodID jm_length = pEnv->GetMethodID(jc_file, "length", "()J");
jlong length = pEnv->CallLongMethod(file, jm_length);
jlong position = 0;
//map result
jclass jc_fileChannel = pEnv->FindClass("java/nio/channels/FileChannel");
jmethodID jm_map = pEnv->GetMethodID(jc_fileChannel, "map",
"(Ljava/nio/channels/FileChannel$MapMode;JJ)Ljava/nio/MappedByteBuffer;");
if (jm_map == nullptr){
LOGE("map 方法未找到")
}
jobject result = pEnv->CallObjectMethod(fileChannel, jm_map, read_only, position, length);
return result;
}
特么的浪费我两天时间,谷歌的Androidstudio报错,快捷修改会将参数或者返回的“$”改成“/”。