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

相关内容

热门资讯

透视实锤!aapoker免费透... 透视实锤!aapoker免费透视脚本(透视)aapoker能控制牌吗,AA德州教程(有挂规律);1、...
透视ai!wepoker有人用... 透视ai!wepoker有人用过吗,黑侠破解wepoker(详细一直输的号能继续打)1、该软件可以轻...
透视黑科技!aapoker怎么... 透视黑科技!aapoker怎么控制牌(透视)aapoker如何设置胜率,普及教程(有挂揭秘);1、a...
透视玄学!wepoker脚本,... 透视玄学!wepoker脚本,wepokerplus开挂(详细透视底牌);1、进入到wepokerp...
透视模拟器!aapoker发牌... 透视模拟器!aapoker发牌逻辑(透视)aapoker免费透视脚本,2025新版(有挂规律)1、在...
透视安装!wepoker透视有... 透视安装!wepoker透视有用吗,wepoker轻量版透视(详细正确养号方法)1、让任何用户在无需...
透视好友房!aapoker怎么... 透视好友房!aapoker怎么选牌(透视)aapoker透视插件,2025新版(有挂工具);1、许多...
透视新版!wepoker透视脚... 透视新版!wepoker透视脚本下载,wepoker游戏的安装教程(详细破解游戏盒子)小薇(透视辅助...
透视中牌率!aapoker公共... 透视中牌率!aapoker公共底牌(透视)aapoker辅助怎么用,专业教程(有挂规律)1、下载好a...
透视科技!wepoker有没有... 透视科技!wepoker有没有透视方法,wepoker破解工具(详细作弊辅助)wepoker有没有透...