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

相关内容

热门资讯

有挂透视!wepoker如何设... 有挂透视!wepoker如何设置透视!我来教大家辅助挂(有挂方法)-哔哩哔哩1)wepoker如何设...
解迷透视!wpk私人局辅助是真... 解迷透视!wpk私人局辅助是真的吗!盘点十款辅助软件(讲解有挂)-哔哩哔哩1、wpk私人局辅助是真的...
推荐透视!德州真人透视脚本!热... 推荐透视!德州真人透视脚本!热点讨论辅助攻略(有挂秘籍)-哔哩哔哩1、上手简单,内置详细流程视频教学...
专业透视!we poker辅助... 专业透视!we poker辅助器!玩家必备教程辅助脚本(有挂头条)-哔哩哔哩1、每一步都需要思考,不...
解迷透视!德普之星app安卓版... 解迷透视!德普之星app安卓版破解版!玩家科普辅助攻略(发现有挂)-哔哩哔哩在进入德普之星app安卓...
科普透视!wepoker手机插... 科普透视!wepoker手机插件!传递经验辅助方法(果真有挂)-哔哩哔哩1、进入游戏-大厅左侧-新手...
解密透视!we poker辅助... 解密透视!we poker辅助器下载!交流学习经验辅助技巧(有挂透视)-哔哩哔哩1、进入到we po...
详情透视!红龙poker辅助器... 详情透视!红龙poker辅助器免费观看!推荐攻略辅助技巧(有挂解密)-哔哩哔哩1、红龙poker辅助...
有挂透视!wepoker好友助... 有挂透视!wepoker好友助力码!推荐十款辅助软件(确实有挂)-哔哩哔哩运wepoker好友助力码...
开挂透视!wepoker透视脚... 开挂透视!wepoker透视脚本免费使用视频!推荐攻略辅助软件(有挂工具)-哔哩哔哩;1.wepok...