我目前正在使用以下代码使用 SAF 在 Lollipop 上的 MicroSD 中创建子文件夹
String[] folders = fullFolderName.replaceFirst(UriFolder + "/", "").split("/");
//fullFolderName is a String which represents full path folder to be created
//Here fullFolderName = /storage/MicroSD/MyPictures/Wallpapers
///storage/MicroSD/MyPictures/ already exists
//Wallpapers is the folder to be created
//UriFolder is String and contains /storage/MicroSD
//folders[] will have folders[0]="MyPictures" folders[1]="Wallpapers"
DocumentFile Directory = DocumentFile.fromTreeUri(context, Uri.parse(treeUri));
//treeUri is the uri pointing to /storage/MicroSD
//treeUri is a Uri converted to String and Stored so it needs to parsed back to Uri
DocumentFile tempDirectory = Directory;
//below loop will iterate and find the MyPictures or the parent
//directory under which new folder needs to be created
for(int i=0; i < folders.length-1; i++)
{
for(DocumentFile dir : Directory.listFiles())
{
if(dir.getName() != null && dir.isDirectory())
{
if (dir.getName().equals(folders[i]))
{
tempDirectory = dir;
break;
}
}
}
Directory = tempDirectory;
}
Directory.createDirectory(folders[folders.length-1]);
上面的代码工作正常并创建了子目录,但是创建文件夹需要大约 5 秒。我是 SAF 的新手,这是定位子目录的唯一方法还是有其他有效的方法来创建子目录?
我将使用内部存储
new File(fullFolderName).mkdir();
这将在几分之一秒内创建文件夹。
最佳答案
这里有一个有点高效的创建方式
public static boolean createFolderUsingUri(String fullFolderName,String treeUri,
String UriFolder,Context ctx)
{
String[] folders = fullFolderName.replaceFirst(UriFolder + "/", "").split("/");
//fullFolderName is a String which represents full path folder to be created
//Example: fullFolderName = /storage/MicroSD/MyPictures/Wallpapers
//The path /storage/MicroSD/MyPictures/ already exists
//Wallpapers is the folder to be created
//UriFolder is String and contains string like /storage/MicroSD
//folders[] will have folders[0]="MyPictures" folders[1]="Wallpapers"
//treeUri string representation of Uri /storage/MicroSD
//Ex: treeUri content://uritotheMicroSdorSomepath.A33%0A
DocumentFile Directory = DocumentFile.fromTreeUri(ctx, Uri.parse(treeUri));
for(int i=0; i < folders.length-1; i++)
{
Directory=Directory.findFile(folders[i]);
}
Directory.createDirectory(folders[folders.length-1]);
return true;
}
问题中描述的方法耗时约 5 秒,而此方法耗时约 3 秒。在 CM 文件管理上,同一路径上的文件夹创建花费了 ~4 秒,因此这是相对更快的方法。然而,搜索更快的方法将花费 < 1 秒
关于android - 如何使用存储访问框架高效地创建子文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163488/