如何使用Storage Access Framework高效创建子文件夹?

时间:2015-08-23 05:27:39

标签: android storage-access-framework

我目前正在使用以下代码在Lollipop上使用SAF在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();

这将在几分之一秒内创建文件夹。

1 个答案:

答案 0 :(得分:1)

这是一种创建

的有效方法
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秒,所以这是比较快的方法。然而,搜索更快的方式将采取&lt; 1秒