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手机助手,wepoker数据分析工具,指南教程(有挂规律)-哔哩哔哩1、每一...
辅助透视!拱趴大菠萝万能挂!一... 辅助透视!拱趴大菠萝万能挂!一贯是真的有辅助插件(有挂方针)-哔哩哔哩亲,关键说明,拱趴大菠萝万能挂...
开挂透视!hhpoker有没有... 开挂透视!hhpoker有没有作必弊挂,wepoker到底有没有透视,绝活儿教程(有挂辅助)-哔哩哔...
普及透视!竞技联盟透视!都是存... 普及透视!竞技联盟透视!都是存在有辅助工具(有挂方式)-哔哩哔哩1、完成竞技联盟透视辅助器v3.3的...
开挂透视!wepoker有脚本... 开挂透视!wepoker有脚本吗,德州机器人代打脚本,模块教程(有人有挂)-哔哩哔哩1、首先打开德州...
有挂透视!poker worl... 有挂透视!poker world辅助!原来有辅助脚本(有挂方针)-哔哩哔哩poker world辅助...
揭幕透视!红龙poker作必弊... 揭幕透视!红龙poker作必弊指令,德州透视是真的假的,妙招教程(有挂猫腻)-哔哩哔哩1、德州透视是...
揭幕透视!sohoo poke... 揭幕透视!sohoo poker辅助!一贯一直总是有辅助脚本(有挂攻略)-哔哩哔哩1、sohoo p...
科普透视!hhpoker一直输... 科普透视!hhpoker一直输有挂吗,有没有人wepoker,妙招教程(有挂秘笈)-哔哩哔哩一、hh...
解迷透视!werplan免费挂... 解迷透视!werplan免费挂下载!都是是有辅助app(有挂规律)-哔哩哔哩一、werplan免费挂...