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透视有吗,智星德州插件最新版本更新内容详解-都是是真的有辅助工具(哔哩哔哩)...
外挂经验!哈糖大菠萝破解器,w... 外挂经验!哈糖大菠萝破解器,werplan免费挂下载-确实真的是有辅助神器(哔哩哔哩)进入游戏-大厅...
外挂演示!werplan辅助软... 外挂演示!werplan辅助软件,pokemomo辅助工具-果然一直都是有辅助工具(哔哩哔哩)1、外...
外挂项目!hardrock透视... 外挂项目!hardrock透视工具,agpoker辅助-一直一直都是有辅助app(哔哩哔哩)1、让任...
外挂阶段!fishpoker透... 外挂阶段!fishpoker透视底牌,pokerworld破解版下载-其实有辅助神器(哔哩哔哩)po...
外挂窍门!聚星ai辅助工具激活... 外挂窍门!聚星ai辅助工具激活码,佛手在线大菠萝智能辅助器-好像是真的有辅助插件(哔哩哔哩)1、全新...
外挂演示!德扑圈透视,德普之星... 外挂演示!德扑圈透视,德普之星透视辅助软件激活码-都是真的有辅助神器(哔哩哔哩)该软件可以轻松地帮助...
外挂学习!扑克之星辅助,德州透... 外挂学习!扑克之星辅助,德州透视插件-其实一直都是有辅助软件(哔哩哔哩)1、不需要AI权限,帮助你快...
外挂秘籍!智星菠萝透视,约局吧... 外挂秘籍!智星菠萝透视,约局吧德州真的存在透视吗-都是有辅助方法(哔哩哔哩)1、上手简单,内置详细流...
外挂讲义!uupoker透视,... 外挂讲义!uupoker透视,pokermaster辅助器-确实有辅助脚本(哔哩哔哩)1、玩家可以在...