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

相关内容

热门资讯

透视ai!wpk辅助ai,we... 透视ai!wpk辅助ai,wepoker透视底牌,高科技教程(原先真的是有挂);wepoker透视黑...
透视私人局!wepoker辅助... 透视私人局!wepoker辅助工具,aapoker辅助功能,免费测试版(有挂了解)(1)透视私人局!...
透视插件!德普之星透视辅助插件... 透视插件!德普之星透视辅助插件,wpk透视脚本下载,一分钟秒懂(有挂介绍);一、德普之星透视辅助插件...
透视ai代打!红龙poker脚... 透视ai代打!红龙poker脚本,wepoker正确养号方法,2025新版教程(竟然有挂);揭秘教程...
透视规律!wepoker透视版... 透视规律!wepoker透视版下载,aapoker辅助包,玩家分享(有挂透明)是一款可以让一直输的玩...
透视好友房!德普之星辅助器,w... 透视好友房!德普之星辅助器,wepoker免费透视脚本,总算清楚(有挂技巧);一、wepoker免费...
透视能赢!aapoker透视脚... 透视能赢!aapoker透视脚本安装包,智星菠萝可以辅助吗,教你攻略(切实真的是有挂) 科技详细教程...
透视挂!aapoker辅助挂,... 透视挂!aapoker辅助挂,wepoker辅助器下载,推荐十款(有挂技巧)1、不需要AI权限,帮助...
透视好友!智星菠萝可以辅助吗,... 透视好友!智星菠萝可以辅助吗,epoker透视底牌,技巧教程(起初真的有挂);实战中需综合运用上述技...
透视辅助!wepoker辅助器... 透视辅助!wepoker辅助器安装包,aapoker透视插件下载,总算了解(有挂方法)1、快速入门:...