Android 11 如何通过fileprovider读写文件
时间: 2024-05-16 16:13:41 浏览: 24
在Android 11中,由于对文件访问权限进行了限制,使用FileProvider来读写文件已经成为了一种标准的方式。
以下是使用FileProvider读写文件的步骤:
1. 在AndroidManifest.xml文件中定义FileProvider:
```
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="包名.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
```
其中,`android:authorities`是FileProvider的标识符,`android:grantUriPermissions`表示是否授予其他应用访问权限,`android:exported`表示是否允许其他应用调用。
2. 在res/xml目录下创建file_paths.xml文件,定义FileProvider的路径:
```
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="my_images"
path="Pictures" />
</paths>
```
其中,`<external-files-path>`表示文件的路径,`name`是自定义的名称。
3. 在代码中使用FileProvider读写文件:
```
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "test.jpg");
Uri uri = FileProvider.getUriForFile(this, "包名.fileprovider", file);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
// 读取文件内容
OutputStream outputStream = getContentResolver().openOutputStream(uri);
// 写入文件内容
} catch (IOException e) {
e.printStackTrace();
}
```
其中,`FileProvider.getUriForFile()`方法将文件转换为Uri,`getContentResolver().openInputStream()`方法和`getContentResolver().openOutputStream()`方法分别用于读取和写入文件内容。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)