我目前正在使用下面的代码在MicroSD上使用SAF创建子文件夹
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秒