无法在Android Studio中打开外部文件

问题描述 投票:0回答:1

我想使用 Android Studio 中的 NDK 在 C++ 中打开

.npy
文件。外部存储目录位于
/storage/emulated/0/
,所以我使用以下C++代码来打开文件:

#include <stdio.h>
#include <jni.h>
extern "C" JNIEXPORT jint JNICALL
Java_com_example_demo_MainActivity_getInt( JNIEnv* env, jobject /* this */) {
    std::string fname = "/storage/emulated/0/data.npy";
    FILE* fp = fopen(fname.c_str(), "rb");
    if(!fp) throw std::runtime_error("npy_load: Unable to open file "+fname);
    return 0;
}

我在

AndroidManifest.xml
中指定了以下外部存储访问权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   <!-- more stuff -->
</manifest>

但是,我无法正确读取该文件:

terminating with uncaught exception of type std::runtime_error: npy_load: Unable to open file /storage/emulated/0/data.npy

我无法弄清楚为什么这个错误不断发生,因为我对该目录具有读/写访问权限。

android c++ android-studio android-ndk
1个回答
0
投票

Android 对任意路径的使用越来越严格,因此您可能无法访问某些位置(读取或写入),并且无法使用任何 Android 权限来更改它。 根据您的使用情况,如果可以选择,请使用您的应用程序可用的文件夹之一。 例如,从 java/kotlin 您可以检索

的值
getExternalFilesDir(null)?.absolutePath?.let { configDirPath(it) }

并将其传递给本地人,如下所示:

private external fun configDirPath(path: String)

如果目录尚不存在,请不要忘记创建目录。

val extDir = File(getExternalFilesDir(null)!!.absolutePath, "")
if (!extDir.exists()) extDir.mkdirs()

此路径不需要读取或写入权限,它是公共的,如果需要,您可以使用 adb Push 将文件拖放到那里。

© www.soinside.com 2019 - 2024. All rights reserved.