如何在android API33中,将文件写入公区目录下?
时间: 2023-11-28 17:50:12 浏览: 39
在Android 11(API级别30)及更高版本中,应用程序不再具有自由访问公共存储空间,因此您不能直接将文件写入公共存储空间。相反,您应该使用MediaStore API将文件添加到媒体库,或使用Storage Access Framework(SAF)请求用户授权来访问公共存储空间。
以下是一些用于在Android 11及更高版本中使用SAF进行文件写入的示例代码:
```java
private void writeFileToPublicDirectory(Uri uri) {
try {
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write("Hello, world!".getBytes());
fileOutputStream.close();
pfd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
```
在此示例中,您需要使用`getContentResolver().openFileDescriptor()`方法获取文件的`ParcelFileDescriptor`,然后使用`FileOutputStream`将数据写入文件。最后,一定要调用`close()`方法以确保资源被正确释放。
请注意,您需要在`AndroidManifest.xml`文件中添加以下权限声明:`<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>`。但是,这不会授予您直接访问公共存储空间的权限。相反,您需要使用SAF来访问公共存储空间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)