3

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

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

4

1 回答 1

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 秒,因此这是一种相对较快的方法。然而,寻找更快的方式,这将需要 < 1 秒

于 2015-08-25T16:34:48.277 回答