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私人局透视-确实是真的有辅助神器(哔哩哔哩)1、下载...
透视科普!wpk透视是真的假的... 透视科普!wpk透视是真的假的,wpk软件是正规的吗-真是存在有辅助软件(哔哩哔哩)1、金币登录送、...
透视解密!wepoker辅助真... 透视解密!wepoker辅助真的假的,We poker辅助器下载-真是真的有辅助神器(哔哩哔哩)亲,...
透视推荐!hhpoker辅助软... 透视推荐!hhpoker辅助软件,hhpoker德州有挂吗-果然是有辅助神器(哔哩哔哩)1、模拟器是...
透视科普!wpk透视是真的假的... 透视科普!wpk透视是真的假的,wpk辅助器是真的吗-真是是真的有辅助攻略(哔哩哔哩)1、有没有辅助...
透视曝光!wepoker可以透... 透视曝光!wepoker可以透视码,wejoker内置辅助-本来有辅助教程(哔哩哔哩)1、该软件可以...
透视揭露!wepoker破解工... 透视揭露!wepoker破解工具,wepoker怎么设置盖牌-本来一直总是有辅助方法(哔哩哔哩)1、...
透视有挂!有哪些免费的wpk作... 透视有挂!有哪些免费的wpk作弊码,wpk辅助器是真的吗-果然一直总是有辅助脚本(哔哩哔哩)1、公共...
透视关于!德扑圈透视挂,德普之... 透视关于!德扑圈透视挂,德普之星透视辅助-好像是真的有辅助软件(哔哩哔哩)脚本下载中分为三种模型:挂...
透视解密!德普辅助器怎么用,德... 透视解密!德普辅助器怎么用,德普之星透视-好像是有辅助app(哔哩哔哩)1、完成辅助器v3.3的残局...