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

相关内容

热门资讯

透视线上!樱花之盛正版辅助器免... 透视线上!樱花之盛正版辅助器免费,德州透视是真的吗(辅助挂)详细开挂辅助挂;打开点击测试直接进入微信...
推荐攻略!吉祥填大坑脚本小程序... 吉祥填大坑脚本小程序开挂教程视频分享装挂详细步骤在当今的网络游戏中,吉祥填大坑脚本小程序作为一种经典...
透视能赢!uupoker透视,... wepoker手机助手开挂教程视频分享装挂详细步骤在当今的网络游戏中,wepoker手机助手作为一种...
一起来探讨!唯思竞技修改器,微... 一起来探讨!唯思竞技修改器,微乐家乡app插件(详细教程辅助开挂软件);打开点击测试直接进入微信(1...
透视智能ai!途游游戏辅助脚本... 透视智能ai!途游游戏辅助脚本,xpoker辅助器(辅助挂)详细开挂辅助工具;亲,途游游戏辅助脚本这...
玩家必看!广丰中至510k辅助... 玩家必看!广丰中至510k辅助,微信小程序多乐辅助器(有挂分享开挂辅助下载)您好:微信小程序多乐辅助...
透视数据!天天互娱软件,wep... 您好:这款wepoker怎么增加运气游戏是可以开挂的,确实是有挂的,很多玩家在这款wepoker怎么...
科技通报!多乐跑的快脚本,边锋... 科技通报!多乐跑的快脚本,边锋老友威海荣成辅助(有挂教学开挂辅助软件);无需打开直接搜索加(薇:13...
透视辅助!wepoker的辅助... 【亲,线上德州的辅助器是什么 这款游戏可以开挂的,确实是有挂的,很多玩家在这款线上德州的辅助器是什么...
最新技巧!哥哥打大a有没有辅助... 您好:这款哥哥打大a有没有辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款哥哥打大a有没有辅助游戏...