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

相关内容

热门资讯

我来向大家传授!wpk私人局辅... 我来向大家传授!wpk私人局辅助是真的吗,sohoo poker辅助器,竟然是有挂(有挂细节)1、不...
盘点一款!pokemmo辅助工... 盘点一款!pokemmo辅助工具,hh poker插件下载,总是是有挂(有挂辅助)1、玩家可以在线上...
交流学习经验!德普之星怎么设置... 交流学习经验!德普之星怎么设置埋牌,德州hhpoker脚本,确实存在有挂(有挂方针)小薇(辅助器软件...
分享个大家!哈糖大菠萝软件下载... 分享个大家!哈糖大菠萝软件下载,线上德州的辅助器是什么,好像是有挂(有挂详情)1、点击下载安装,脚本...
避坑细节!wpk辅助,soho... 避坑细节!wpk辅助,sohoo poker辅助器,总是有挂(证实有挂)该软件可以轻松地帮助玩家将外...
科技通报!德普之星透视辅助,哈... 科技通报!德普之星透视辅助,哈糖大菠萝免费辅助器,其实真的有挂(有挂透明挂)哈糖大菠萝免费辅助器透视...
实测发现!hhpoker万能辅... 实测发现!hhpoker万能辅助器,wpk显示有作弊,竟然是真的有挂(真实有挂)一、可以开透视的定义...
玩家攻略推荐!wpk模拟器,w... 玩家攻略推荐!wpk模拟器,wpk系统是否存在作弊行为,本来存在有挂(有人有挂)1、任何透视是真的假...
实操分享!竞技联盟透视插件,哈... 实操分享!竞技联盟透视插件,哈糖大菠萝可以开挂吗,原来是真的有挂(有挂方式)1、首先打开辅助器下载最...
玩家必看教程!wepoker可... 玩家必看教程!wepoker可以免费玩吗,hhpoker买挂,切实有挂(有挂实锤)破解侠是真的助透视...