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时,需要请求用户授予应用访问外部存储器的权限,并且需要检查用户是否已经开启了外部存储器管理器的权限。如果用户未开启该权限,需要通过应用引导用户进行设置。

相关内容

热门资讯

实测分享!wepoker免费钻... 实测分享!wepoker免费钻石,约局吧游戏挂,必赢方法(有挂软件)关于wepoker免费钻石机制的...
揭秘真相!pokemmo脚本辅... 揭秘真相!pokemmo脚本辅助下载,hhpoker的辅助是真的吗,必备教程(有挂神器);1分钟了解...
重要通知!xpoker怎么作弊... 重要通知!xpoker怎么作弊,德州局怎么透视,细节方法(有挂技巧);德州局怎么透视软件透明挂更新新...
教学盘点!we poker辅助... 教学盘点!we poker辅助器v3.3,aapoker透视方法,详细教程(有挂教程)科技教程也叫必...
热点推荐!hhpkoer辅助器... 热点推荐!hhpkoer辅助器视频,wepoker破解版内购,必胜教程(有挂神器);1.hhpkoe...
三分钟了解!wejoker辅助... 1、三分钟了解!wejoker辅助脚本,wpk作弊最怕三个东西,新2025教程(有挂攻略)(UU p...
盘点十款!wpk俱乐部辅助器,... 盘点十款!wpk俱乐部辅助器,wepoker免费透视,攻略教程(有挂透视);1分钟了解详细教程(微信...
免费测试版!约局吧德州有挂吗,... 免费测试版!约局吧德州有挂吗,拱趴大菠萝辅助神器,详细教程(有挂神器);小薇(透视辅助)致您一封信;...
玩家攻略推荐!poker wo... 玩家攻略推荐!poker world辅助,hhpkoer辅助挂是真的吗,我来教教你(有挂技巧);1分...
最新研发!哈糖大菠萝怎么开挂,... 最新研发!哈糖大菠萝怎么开挂,哈糖大菠萝挂,教你攻略(有挂辅助);致您一封信;亲爱哈糖大菠萝怎么开挂...