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

相关内容

热门资讯

透视了解"哈糖大菠萝... 透视了解"哈糖大菠萝免费辅助器"都是是有辅助技巧(哔哩哔哩)该软件可以轻松地帮助玩家将哈糖大菠萝免费...
最新消息"wepok... 最新消息"wepoker有机器人吗"安装不了wepoker(一直存在有辅助下载)-哔哩哔哩1.wep...
最终"aapoker... 最终"aapoker辅助软件合法吗"uupoker透视(好像是有辅助下载)-哔哩哔哩1.aapoke...
透视科普"wepok... 透视科普"wepoker透视脚本免费使用视频"切实真的有辅助器(哔哩哔哩)1、完成wepoker透视...
透视解迷"wepok... 透视解迷"wepokerplus外开挂"真是真的有辅助技巧(哔哩哔哩)1、让任何用户在无需wepok...
透视规律"拱趴大菠萝... 透视规律"拱趴大菠萝万能挂"pokemmo手机辅助软件(切实真的有辅助安装)-哔哩哔哩1、超多福利:...
透视总结"德普软件&... 透视总结"德普软件"真是真的是有辅助教程(哔哩哔哩)1、德普软件公共底牌简单,德普软件透视插件操作,...
透视脚本"破解辅助插... 透视脚本"破解辅助插件wepoker"wepoker怎么开辅助(一直真的是有辅助神器)-哔哩哔哩1、...
透视解迷"wepok... 透视解迷"wepoker私人局辅助"切实是真的辅助方法(哔哩哔哩)1、打开软件启动之后找到中间准星的...
有消息称"wepok... 有消息称"wepoker免费钻石"德州局透视脚本(确实存在有辅助下载)-哔哩哔哩1、下载好德州局透视...