android jni中读写文件的代码
时间: 2023-12-06 20:04:02 浏览: 163
读取文件:
```java
JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_readFile(JNIEnv *env, jobject instance,
jstring fileName_) {
const char *fileName = (*env)->GetStringUTFChars(env, fileName_, 0);
FILE *file = fopen(fileName, "r");
if (file == NULL) {
return (*env)->NewStringUTF(env, "");
}
char buffer[1024];
size_t len;
char *result = (char *) malloc(1);
result[0] = '\0';
while ((len = fread(buffer, 1, sizeof(buffer), file)) > 0) {
result = (char *) realloc(result, strlen(result) + len + 1);
strncat(result, buffer, len);
}
fclose(file);
(*env)->ReleaseStringUTFChars(env, fileName_, fileName);
return (*env)->NewStringUTF(env, result);
}
```
写入文件:
```java
JNIEXPORT jboolean JNICALL
Java_com_example_myapplication_MainActivity_writeFile(JNIEnv *env, jobject instance,
jstring fileName_, jstring content_) {
const char *fileName = (*env)->GetStringUTFChars(env, fileName_, 0);
const char *content = (*env)->GetStringUTFChars(env, content_, 0);
FILE *file = fopen(fileName, "w");
if (file == NULL) {
return JNI_FALSE;
}
fwrite(content, strlen(content), 1, file);
fclose(file);
(*env)->ReleaseStringUTFChars(env, fileName_, fileName);
(*env)->ReleaseStringUTFChars(env, content_, content);
return JNI_TRUE;
}
```
阅读全文