gpt4 book ai didi

android - 在外部存储上创建新文件时权限被拒绝

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:16:22 26 4
gpt4 key购买 nike

我需要将文件从 Assets 复制到外部存储。这是我的代码:

    File f = new File(Environment.getExternalStorageDirectory() + File.separator
+ "MyApp" + File.separator + "tessdata" + File.separator + "eng.traineddata");
if (!f.exists()) {
AssetManager assetManager = getAssets();
try {
f.createNewFile();
InputStream in = assetManager.open("eng.traineddata");
OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator
+ "MyApp" + File.separator + "tessdata" + File.separator + "eng.traineddata");
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
out.write(buffer, 0, read);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: ", e);
}
}

我还在 list 中添加了权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

执行f.createNewFile()时出现异常,提示“Permission denied”。

请问我该如何解决?

最佳答案

在我的例子中,这是由于 API 23+ 所需的权限弹出窗口,即使您在 list 中添加了权限也是如此。

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}

在应用启动时或您需要权限时调用此函数。

AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

权限的详细示例代码可以在 here 中找到。

关于android - 在外部存储上创建新文件时权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16360763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com