JNI 对文件读写操作:
1.读取本地文件
extern "C" JNIEXPORT void JNICALL
Java_com_xinrui_ndkapp_MainActivity_readFile(JNIEnv *env, jobject instance,jstring str) {
const char* path=env->GetStringUTFChars(str,JNI_FALSE);
FILE* file = fopen(path,"r");
if(file==NULL){
LOGE("file open failed");
}
char buffer[1024]={0};
while(fread(buffer, sizeof(char),1024,file)!=0){
LOGE("content:%s",buffer);
}
if(file!=NULL){
fclose(file);
}
env->ReleaseStringUTFChars(str,path);
}
2.读取文件并写入到其他文件
extern "C" JNIEXPORT void JNICALL
Java_com_xinrui_ndkapp_MainActivity_readwriteFile(JNIEnv *env, jobject instance,jstring source_str,jstring dest_str) {
const char* sourcestr = env->GetStringUTFChars(source_str,JNI_FALSE);
const char* deststr = env->GetStringUTFChars(dest_str,JNI_FALSE);
FILE * fp;
FILE * fd;
char buf[1024];
fp=fopen(sourcestr,"rw");
if(fp==NULL) {
LOGE("open source filed");
}
fd=fopen(deststr,"w");//当文件不存在时,自动创建该文件
if(fd==NULL) {
LOGE("open dest filed");
}
while(fgets(buf, sizeof(buf),fp)!=NULL){
fputs(buf,fd);
}
if(fp!=NULL){
fclose(fp);
}
if(fd!=NULL){
fclose(fd);
}
env->ReleaseStringUTFChars(source_str,sourcestr);
env->ReleaseStringUTFChars(dest_str,deststr);
}