Android11如何让应用程序有读写SD卡/Android/someapp目录的权限?
创始人
2024-08-20 11:00:41
0

在Android 11中,应用程序默认无法读写SD卡/Android/someapp目录。若需要访问该目录,需要利用媒体存储库(MediaStore)来进行文件I/O操作。以下是一个简单的代码示例:

private static final String RELATIVE_DIRECTORY = "/someapp/"; // 相对目录名
private static final String MIME_TYPE_TEXT = "text/plain"; // 文件类型

// 获取sdcard/Android/someapp目录
public static File getExternalStorageDirectory(Context context) {
    File file;
    if (context.getExternalMediaDirs().length > 0) {
        // 检查应用程序目录是否存在
        file = new File(context.getExternalMediaDirs()[0], RELATIVE_DIRECTORY);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Log.e(TAG, "getExternalStorageDirectory: failed to create directory");
                return null;
            }
        }
    } else {
        Log.e(TAG, "getExternalStorageDirectory: external media dirs length <= 0");
        file = context.getExternalFilesDir(null);
    }
    return file;
}

// 写入文件内容到sdcard/Android/someapp目录
public static boolean writeFileToExternalStorage(Context context, String fileName, String content){
    File file = new File(getExternalStorageDirectory(context), fileName);
    try {
        FileWriter writer = new FileWriter(file, false);
        writer.write(content);
        writer.flush();
        writer.close();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "writeFileToExternalStorage: failed to write file", e);
        return false;
    }
}

// 读取文件内容从sdcard/Android/someapp目录
public static String readFileFromExternalStorage(Context context, String fileName){
    File file = new File(getExternalStorageDirectory(context), fileName);
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line).append("\n");
        }
        reader.close();
        return content.toString

相关内容

热门资讯

目前!白银胡乐修改器!切实真的... 目前!白银胡乐修改器!切实真的有辅助平台(有挂方法)-哔哩哔哩1、完成白银胡乐修改器有辅助插件,帮助...
为了进一步!兴动互娱技巧!总是... 为了进一步!兴动互娱技巧!总是真的有辅助平台(发现有挂)-哔哩哔哩1、不需要AI权限,帮助你快速的进...
长期以来!中至小程序破檞!确实... 长期以来!中至小程序破檞!确实存在有辅助安装(存在有挂)-哔哩哔哩1、该软件可以轻松地帮助玩家将中至...
昨日!来玩app辅助器!果然是... 昨日!来玩app辅助器!果然是有辅助器(发现有挂)-哔哩哔哩1)来玩app辅助器有没有挂:进一步探索...
事发当天!八闽掌上十八卦脚本!... 事发当天!八闽掌上十八卦脚本!总是是真的辅助安装(有挂神器)-哔哩哔哩1、八闽掌上十八卦脚本免费辅助...
经调查!同城游辅助!果然存在有... 经调查!同城游辅助!果然存在有辅助安装(有挂总结)-哔哩哔哩同城游辅助是不是有人用挂微扑克wpk插件...
随着!微乐河南小程序微乐辅助脚... 随着!微乐河南小程序微乐辅助脚本!本来存在有辅助下载(有挂分享)-哔哩哔哩1)微乐河南小程序微乐辅助...
连日来!蜀山四川辅助!果然真的... 连日来!蜀山四川辅助!果然真的有辅助器(有挂头条)-哔哩哔哩在进入蜀山四川辅助软件靠谱后,参与本局比...
截至发稿!小程序财神十三张祈福... 截至发稿!小程序财神十三张祈福!确实是有辅助神器(有挂技巧)-哔哩哔哩截至发稿!小程序财神十三张祈福...
于此同时!随意玩怎么创建聚乐部... 于此同时!随意玩怎么创建聚乐部!原来有挂辅助器(果真有挂)-哔哩哔哩1、随意玩怎么创建聚乐部免费辅助...