Android11中出现java.io.FileNotFoundException:openfailed:ENOENT(Nosuchfileordirectory)错误
创始人
2024-09-30 17:00:31
0

在Android 11中,应用的文件访问权限得到了加强,因此在访问外部存储器中的文件时,需要使用特定的方法来处理。以下是一个示例代码来读取外部存储上的文件:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
        && Environment.isExternalStorageManager()) {

    // Use the MediaStore API to read the file
    Uri uri = MediaStore.Downloads.EXTERNAL_CONTENT_URI.buildUpon().appendPath(filename).build();
    ContentResolver contentResolver = getContentResolver();
    String[] projection = {MediaStore.Downloads._ID, MediaStore.Downloads.DISPLAY_NAME, 
        MediaStore.Downloads.SIZE};
    try (Cursor cursor = contentResolver.query(uri, projection, null, null, null)) {
        int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID);
        int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads.DISPLAY_NAME);
        int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads.SIZE);
        if (cursor.moveToFirst()) {
            Log.d(TAG, "Found file " + cursor.getString(nameColumn) + " with size " + 
                cursor.getInt(sizeColumn));
            // Use the content resolver to open a stream to read the file
            try (InputStream is = contentResolver.openInputStream(uri)) {
                // Read the file as needed...
            } catch (IOException e) {
                Log.e(TAG, "Failed to read file", e);
            }
        } else {
            Log.e(TAG, "File not found");
        }
    } catch (Exception e) {
        Log.e(TAG, "Failed to retrieve file", e);
    }
} else {
    // Use legacy methods to read the file
    // For example, use the File API to open a FileInputStream
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
    try (FileInputStream is = new FileInputStream(file)) {
        // Read the file as needed...
    } catch (IOException e) {
        Log.e(TAG, "Failed to read file", e);
    }
}

在使用MediaStore API时,需要请求用户授予应用访问外部存储器的权限,并且需要检查用户是否已经开启了外部存储器管理器的权限。如果用户未开启该权限,需要通过应用引导用户进行设置。

相关内容

热门资讯

分辨真假!天天爱柳州辅助,决战... 分辨真假!天天爱柳州辅助,决战卡五星辅助修改器,玩家教程(有挂方法)-哔哩哔哩 >>您好:软件加薇1...
玩家必看"阿当比鸡辅... 玩家必看"阿当比鸡辅助器"开挂(透视)辅助插件(一直是真的有挂的)-哔哩哔哩;1、不需要AI权限,帮...
重大来袭!小程序财神十三张辅助... 重大来袭!小程序财神十三张辅助,wepoker私人局俱乐部怎么进,AA德州教程!(有挂助手)-哔哩哔...
玩家必看秘籍"聚财a... 玩家必看秘籍"聚财app辅助"开挂(透视)辅助下载(一贯确实有挂的)-哔哩哔哩相信很多朋友都在电脑上...
一分钟了解!皮皮游戏挂机辅助,... 一分钟了解!皮皮游戏挂机辅助,wejoker辅助机器人,技巧教程(今日头条)-哔哩哔哩 【无需打开直...
科技通报"友友联盟辅... 科技通报"友友联盟辅助器"开挂(透视)辅助软件(其实真的有挂的)-哔哩哔哩;是一款可以让一直输的玩家...
一分钟了解"浙江宝宝... 一分钟了解"浙江宝宝游戏辅助工具"开挂(透视)辅助插件(其实确实有挂的)-哔哩哔哩;是一款可以让一直...
玩家爆料!四川游戏辅助器,德州... 您好:四川游戏辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
每日必备"新西楚有挂... 每日必备"新西楚有挂吗"开挂(透视)辅助插件(原来是真的有挂)-哔哩哔哩;小薇(透视辅助)致您一封信...
透视有挂!广西老友麻将有挂吗,... 透视有挂!广西老友麻将有挂吗,we poker辅助器,靠谱教程(竟然有挂)-哔哩哔哩;无需打开直接搜...