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

标签 android file-io

我需要将文件从 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/

相关文章:

java - 文件对象是否支持所有文件(键盘、目录、文件等)?

python - 打开未知扩展名的现有文件

Android 异常终结器

android - 之后删除了应用程序图标 新包尚未在系统中注册 遇到消息

android - 如何关闭进度条?

go - 我应该在调用os.removeAll之前关闭os.File吗?

c - 经常使用文件定位功能来翻转文件

c - 使用 `posix_fallocate` 创建的修剪文件

java - 如何以编程方式从我的应用程序中过滤和清除其他应用程序缓存?

android - 进行计算并烘烤它---错误