在Android 11中,访问应用程序数据和文件的方式已经发生了变化。默认情况下,应用程序只能访问其私有目录和媒体文件集合。为了访问其他目录,需要获取适当的权限。
对于scoped storage应用程序来说,获取父文件夹权限与获取普通文件夹权限并没有任何区别。只需要从适当的API获取权限。以下是获取父文件夹权限并从子文件夹中读取数据的代码示例:
if (Environment.isExternalStorageManager()) {
// Permission is already granted
// Get the parent folder
File parentFolder = new File(Environment.getExternalStorageDirectory(), "myParentFolder");
if (parentFolder.exists()) {
// Get the child folder
File childFolder = new File(parentFolder, "myChildFolder");
if (childFolder.exists()) {
// Read the file from the child folder
File myFile = new File(childFolder, "myFile.txt");
if (myFile.exists()) {
// Read the contents of the file
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
br.close();
String fileContents = sb.toString();
Log.d(TAG, "File contents: " + fileContents);
} catch (IOException e) {
Log.e(TAG, "Error reading file", e);
}
}
}
}
} else {
// Request permission
Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(intent);
}
在这个示例中,Environment.getExternalStorageDirectory()
返回外部存储设备的根目录。File
类用于创建文件或目录对象。myParentFolder
和myChildFolder
是目录名称。这些名称可以根据需要进行更改。