Android 11引入了Scoped Storage以提高用户数据隐私保护。但在此新机制下,应用程序不能直接访问外部存储上的任何文件。在使用DocumentFile时需将其替换为java.io.File。以下是将DocumentFile移动到java.io.File的示例代码:
// Android 11及更高版本的DocumentFile:
DocumentFile documentFile = DocumentsContract.createDocument(getContext().getContentResolver(), "image/png", "MyImage.png");
InputStream inputStream = getContentResolver().openInputStream(documentFile.getUri());
// 复制文件
File outputFile = new File(getContext().getExternalFilesDir(null), "MyImage.png");
OutputStream outputStream = new FileOutputStream(outputFile);
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
// 替换为java.io.File:
File file = new File(documentFile.getUri().getPath());
在使用java.io.File进行读取或写入数据之前,需要在应用程序中声明适当的权限。