在Android 11中,应用程序无法直接访问文件系统中的文件,而是必须通过相应的URI来访问。此外,应用程序使用的URI类型应该是标准的content://类型而不是file://类型。
以下是使用content URI来读取文件的示例代码:
// Create a ContentResolver instance ContentResolver cr = getContentResolver();
// Define the URI for the file to be read Uri uri = Uri.parse("content://com.example.app.provider/file/sample.txt");
// Open a stream to read the file InputStream is = cr.openInputStream(uri);
// Read the content of the file byte[] buffer = new byte[1024]; int bytesRead = is.read(buffer); while (bytesRead != -1) { // Process the read data ...
// Read the next chunk of data
bytesRead = is.read(buffer);
}
// Close the stream is.close();
注意,上述内容提供商URI的格式必须为'content://authority/path”格式,其中authority是应用程序的包名。
通过这种方式使用URI,应用程序就可以在不访问文件系统的情况下读取文件。