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

相关内容

热门资讯

科技揭秘!约局吧app有挂吗,... 科技揭秘!约局吧app有挂吗,wepoker透视脚本网页,总结教程(有挂技巧);小薇(透视辅助)致您...
一起来讨论!hhpoker是正... 1、一起来讨论!hhpoker是正品吗,大菠萝免费辅助,wpk教程(有挂神器)。2、大菠萝免费辅助透...
推荐十款!aapoker发牌逻... 您好,佛手大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
玩家必看科普!wepoker买... 自定义wepoker买钻石有用吗系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
热点讨论!wepoker透视是... 热点讨论!wepoker透视是真的吗,wepoker手机版辅助,教你教程(有挂透视)1、点击下载安装...
我来教大家!wejoker黑侠... 我来教大家!wejoker黑侠辅助器,wepoker透视脚本免费使用视频,必赢方法(有挂透视);致您...
分享实测!菠萝辅助器免费版的特... 分享实测!菠萝辅助器免费版的特点,we-poker辅助软件教程,靠谱教程(有挂透视);原来确实真的有...
一分钟了解!德州透视是真的吗,... 1、一分钟了解!德州透视是真的吗,德普之星辅助工具如何设置,安装教程(有挂透视)2、进入游戏-大厅左...
玩家攻略推荐!约局吧能不能开挂... 玩家攻略推荐!约局吧能不能开挂,约局吧如何查看是否有挂,扑克教程(有挂神器);支持多人共享记分板与复...
记者揭秘!wepoker辅助分... 1、记者揭秘!wepoker辅助分析器,拱趴大菠萝有什么挂,科技教程(有挂技巧)。2、拱趴大菠萝有什...