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-h5... 普及透视!wepoker-h5下载,微乐如何自己建脚本,举措教程(有挂存在)-哔哩哔哩1、wepok...
揭露透视!epoker底牌透视... 揭露透视!epoker底牌透视,微乐辅助靠谱麻,资料教程(有挂透明挂)-哔哩哔哩1、玩家可以在epo...
总结透视!wepoker免费脚... 总结透视!wepoker免费脚本咨询,微乐自建房脚本如何下载,资料教程(有挂攻略)-哔哩哔哩1.we...
揭露透视!哈糖大菠萝可以开挂吗... 揭露透视!哈糖大菠萝可以开挂吗,微乐多乐跑作弊,大纲教程(有挂透视)-哔哩哔哩1、哈糖大菠萝可以开挂...
关于透视!wpk模拟器,微乐小... 关于透视!wpk模拟器,微乐小程序自建房透视,绝活儿教程(真实有挂)-哔哩哔哩暗藏猫腻,小编详细说明...
详情透视!wepoker私人局... 详情透视!wepoker私人局透视,微乐兰州麻将小程序辅助,讲义教程(有挂方略)-哔哩哔哩详情透视!...
解谜透视!来玩app破解,微乐... 解谜透视!来玩app破解,微乐小程序微乐家乡辅助器,阶段教程(真实有挂)-哔哩哔哩1、这是跨平台的来...
解密透视!pokemmo辅助器... 解密透视!pokemmo辅助器脚本下载,微信小程序微乐破解器2024,总结教程(有挂透视)-哔哩哔哩...
总结透视!wepokerplu... 总结透视!wepokerplus开挂,陕西微乐挖坑控制器,大纲教程(确实有挂)-哔哩哔哩1、这是跨平...
有挂透视!德州私人局脚本,微乐... 有挂透视!德州私人局脚本,微乐辅助和靠谱吗,阶段教程(有挂秘籍)-哔哩哔哩所有人都在同一条线上,像星...