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

相关内容

热门资讯

一分钟揭秘!wepokerpl... 一分钟揭秘!wepokerplus辅助,hh poker辅助器先试用,揭秘攻略(一贯是有挂的)-哔哩...
终于清楚!newpoker怎么... 终于清楚!newpoker怎么安装脚本,we-poker软件,力荐教程(一直是有挂的)-哔哩哔哩;1...
揭秘关于!wepoker钻石怎... 揭秘关于!wepoker钻石怎么看底牌,德普之星的辅助工具介绍,必胜教程(一直确实有挂)-哔哩哔哩;...
一分钟揭秘!uupoker有透... 一分钟揭秘!uupoker有透视吗,hhpoker有没有辅助,新2026版(一贯真的有挂)-哔哩哔哩...
科技通报!hhpoker为什么... 科技通报!hhpoker为什么一直输,wepoker透视脚本苹果版,存在挂教程(原来有挂)-哔哩哔哩...
透视辅助!wepokerplu... 透视辅助!wepokerplus透视脚本免费,wepoker辅助插件功能,必备教程(一贯有挂)-哔哩...
透视辅助!wejoker内置辅... 透视辅助!wejoker内置辅助,hhpoker有辅助的吗,wpk教程(其实真的有挂)-哔哩哔哩,h...
一分钟了解!wepoker透视... 一分钟了解!wepoker透视脚本下载,wepoker怎么看牌型,黑科技教程(其实真的是有挂)-哔哩...
推荐十款!约局吧德州有挂吗,w... 推荐十款!约局吧德州有挂吗,wpk私人局辅助是真的吗,规律教程(一直真的有挂)-哔哩哔哩;wpk私人...
分享实测!模拟器打开hhpok... 分享实测!模拟器打开hhpoker,哈糖大菠萝怎么挂,靠谱教程(原来是有挂)-哔哩哔哩相信很多朋友都...