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

相关内容

热门资讯

wepokeai机器人(透视)... wepokeai机器人(透视)wepoke有没有玄学(详细辅助新2025版)确实是有挂(可靠辅助德之...
wepoke模拟器(透视)we... wepoke模拟器(透视)wepoke软件透明功能实现方法(详细辅助教你教程)好像是真的有挂(科普插...
wepoke辅助德之星(透视)... wepoke辅助德之星(透视)wepooke app系统规律(详细辅助攻略方法)真是是有挂(教你有辅...
wepoke有辅助挂(透视)w... wepoke有辅助挂(透视)wepoke有辅助挂吗(详细辅助科技教程)一直是有挂(教你透视挂)1、让...
wepoke辅助有挂(透视)w... wepoke辅助有挂(透视)wepoke人有挂吗(详细辅助可靠技巧)其实有挂(了解辅助)1.wepo...
wepoke插件(透视)wep... wepoke插件(透视)wepoke软件收费是真的吗(详细辅助辅助教程)其实真的是有挂(专业模拟器)...
wepoke辅助德之星(透视)... wepoke辅助德之星(透视)wopoker辅助(详细辅助新2025教程)真是真的有挂(玩家ai机器...
we辅助poker德之星(透视... we辅助poker德之星(透视)wepoke辅助挂在哪开(详细辅助新2025版)确实是真的有挂(大神...
wepoke黑科技(透视)we... wepoke黑科技(透视)wepoke挂真的假的(详细辅助揭秘攻略)竟然存在有挂(攻略计算辅助)1、...
wepoke智能ai(透视)w... wepoke智能ai(透视)wepower让系统发好牌(详细辅助教你攻略)真是真的有挂(详细有挂)1...