You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 13内部存储创建文件遇Operation not permitted错误求解决

Android 13 设备中创建文件和目录的解决方案

问题背景

运行以下代码在Android 13设备上创建文件时,出现「Operation not permitted」错误:

File file2 = new File(Environment.getExternalStorageDirectory(), "Reporwt.pdf");
if(!file2.exists()) {
    try {
        boolean created = file2.createNewFile();
        Log.i("download", "File created? " + created);
    } catch (IOException e) {
        Log.i("download", e.getMessage());
    }
}

已添加以下权限但问题未解决:

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

核心原因

Android 13 收紧了外部存储权限,WRITE_EXTERNAL_STORAGE 权限已被废弃,且禁止直接在外部存储根目录(Environment.getExternalStorageDirectory())创建文件,即使申请原有权限也无法绕过该限制。

可行解决方案

方案1:使用应用专属存储(推荐)

应用专属存储无需额外权限,文件随应用卸载自动清理,适合保存应用私有数据:

// 获取应用专属外部存储的Documents子目录
File appDocsDir = new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "");
// 确保目录存在
if (!appDocsDir.exists()) {
    appDocsDir.mkdirs();
}
// 创建目标文件
File targetFile = new File(appDocsDir, "Report.pdf");
if (!targetFile.exists()) {
    try {
        boolean isCreated = targetFile.createNewFile();
        Log.i("download", "File created? " + isCreated);
    } catch (IOException e) {
        Log.e("download", e.getMessage());
    }
}

方案2:使用公共存储目录(需特殊权限)

若必须在公共目录(如Downloads、Documents)创建文件,需申请MANAGE_EXTERNAL_STORAGE特殊权限:

  1. 在Manifest中添加权限:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
    tools:ignore="ScopedStorage" />
  1. 代码中主动引导用户授权:
// 检查是否已获取全文件访问权限
if (!Environment.isExternalStorageManager()) {
    Intent permissionIntent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
    Uri packageUri = Uri.fromParts("package", getPackageName(), null);
    permissionIntent.setData(packageUri);
    startActivity(permissionIntent);
}
// 授权成功后创建文件
File publicFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "Report.pdf");
if (!publicFile.exists()) {
    try {
        boolean isCreated = publicFile.createNewFile();
        Log.i("download", "File created? " + isCreated);
    } catch (IOException e) {
        Log.e("download", e.getMessage());
    }
}

注意:MANAGE_EXTERNAL_STORAGE权限属于高风险权限,Google Play对其使用场景有严格审核,仅当应用确实需要访问设备所有文件时才建议使用。

补充说明

  • Android 13 中WRITE_EXTERNAL_STORAGE、READ_EXTERNAL_STORAGE权限已失效,无需再申请;
  • READ_MEDIA_AUDIO/READ_MEDIA_IMAGES/READ_MEDIA_VIDEO仅用于访问媒体类文件,对创建普通文件无帮助。

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:53:25