首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SAF DocumentFile -检查路径是否存在,而不在每个文件夹级别创建每个DocumentFile

SAF DocumentFile -检查路径是否存在,而不在每个文件夹级别创建每个DocumentFile
EN

Stack Overflow用户
提问于 2016-06-22 19:13:35
回答 2查看 2.5K关注 0票数 6

创建映像时,如果要检查"/folder/subfolder/subsubfolder/test/test.txt“文件是否存在,请执行以下操作:

代码语言:javascript
复制
DocumentFile sdCard = ...; // i have already retrieved the sd card root with the users help via SAF

String path = "<SD CARD>/folder/subfolder/subsubfolder/test/test.txt";
List<String> pathParts = Arrays.asList(path.split("/"));
DocumentFile doc = sdCard;
// go through all folders, starting at sd card, to check, if the desired file exists
for (int i = 1; i < pathParts.size(); i++)
{
    DocumentFile nextDoc = doc.findFile(pathParts.get(i));
    if (nextDoc != null)
        doc = nextDoc;
    else
    {
        doc = null;
        break;
    }
}

if (doc == null)
{
    // file does not exist
}
else
{
    // file does exist
}

这是非常慢的,有没有更快的方法至少检查文件是否存在于SD卡上?我不想仅仅为了检查路径是否存在而创建每个DocumentFile ...

EN

回答 2

Stack Overflow用户

发布于 2017-03-02 20:02:50

代码语言:javascript
复制
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri uri = data.getData();
    DocumentFile pickedDir = DocumentFile.fromTreeUri(MainActivity.this, uri);
    String id = DocumentsContract.getTreeDocumentId(uri); 

    /* id is :  "primary:namefolder" if user select a "namefolder" from internal storage. 
     or CABB-5641 if user select external storage,
    */

    id = id + "/folder/subfolder/subsubfolder/test/test.txt";  // your path,  you must to ensure is consistent with that chosen by the user,

    Uri childrenUri = DocumentsContract.buildDocumentUriUsingTree(uri,id);
    DocumentFile chhildfile = DocumentFile.fromSingleUri(MainActivity.this,childrenUri);

    if(chhildfile != null && chhildfile.exists()){
        Log.d("laporan file", "file ini ada");
    }
}

我不是专家,我不知道这是否能在大多数android上工作,但我已经在Android模拟器和华硕Zenfone 5中尝试过,希望这能有所帮助

票数 10
EN

Stack Overflow用户

发布于 2022-03-04 01:27:48

你不能直接用

String Muri = uri.toString();

然后对每个文件夹uri使用共享首选项,然后在需要时调用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37966386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档