SAF - Attempting to create again an existing folder/file yields a new folder/file

本小妞迷上赌 提交于 2019-12-25 01:15:21

问题


Is SAF intended to replace File handling in external directories, in a certain future?

I hope it is not so in the end, but I am testing SAF itself in advance. It would be useful for other reasons too.

Let's say I am using this method:

static public DocumentFile createFolderInFolder(Activity activity,String            parentFolderUriString,String folderName)
{
DocumentFile result=null;
ContentResolver contentResolver;
contentResolver = activity.getContentResolver();
Uri parentFolderUri=null;
Uri oldParentUri = Uri.parse(parentFolderUriString);
String id = DocumentsContract.getTreeDocumentId(oldParentUri);
parentFolderUri= DocumentsContract.buildChildDocumentsUriUsingTree(oldParentUri,id);
DocumentFile parentFolder = DocumentFile.fromTreeUri(activity, parentFolderUri);
result=parentFolder.createDirectory(folderName);
return result;
}

It creates a directory inside another directory.

When attempting to create an existing folder, for instance "folderName", a new folder is created with a similar name "folderName (1)".

Is there a way to avoid this, so that a new folder is not created if existing? (And the same for files)


回答1:


parentFolderUri= DocumentsContract .buildChildDocumentsUriUsingTree(oldParentUri,id);

For creation in the right directory that should be .buildChildDocumentsUriUsingTree(oldParentUri,id + "/" + folderName);

Further you should start programming two functions. One to check if a directory exists and one for file existence.

To check if a directory exists you would query() the content provider for the (directory+dirName) uri. If you get exceptions the directory does not exist.

For file existence try to use the OpenInputStream of the content resolver on the file uri. If it opens the file exists. If you get exceptions the file does not exist.

Update: If you want to check if a folder exists in a path you obtained with ACTION_OPEN_DOCUMENT_TREE you can use:

static public boolean folderExists(Activity activity, String rootPath, String folderName)
{
    return DocumentFile.fromTreeUri(activity, Uri.parse(rootPath)).findFile(folderName)!=null;

}


来源:https://stackoverflow.com/questions/58094637/saf-attempting-to-create-again-an-existing-folder-file-yields-a-new-folder-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!