准备
作为测试,首先要先把文件从PC上传到Android手机中,可通过命令实现。通过以下命令就可以把pc上test目录下的所有文件传到Android手机中的/sdcard/testfolder/目录下。
adb shell mkdir -p /sdcard/testfolder/
adb push pc_dir/test/ /sdcard/testfolder/
编写NDK接口
在NDK中用C读取文件时首先需要通过Java语言拿到地址,具体地可通过String类型传递文件地址到NDK中。
Example:
public static native int loadFile(String filePath);
在NDK中拿到地址后,需要把String类型的参数转化为C语言的char *,下面转换的示例代码
JNIEXPORT jint JNICALL Java_com_guigu_loadFile
(JNIEnv *env, jclass obj, jstring filePath)
{
const char* testfilePath = env->GetStringUTFChars(filePath, 0);
if(testfilePath == NULL ) {
return -1;
}
/*********************************************/
//read and operate the file, or doing something
/*********************************************/
env->ReleaseStringUTFChars(filePath, testfilePath);
return 0;
}
在Java层调用JNI接口
在调用接口前,需要在Java层获得文件路径,然后作为参数传进去。
File sdcard = Environment.getExternalStorageDirectory();
String fileDir = sdcard.getAbsolutePath() + "/testfolder/test.txt";
int result = testClasee.loadFile(fileDir);
ps: 在操作文件时一定要小心int, long, unsigned long等类型在不同平台的长度大小是否与写文件时匹配,博主被这个问题坑了两天。