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

标签 android storage-access-framework documentfile

想象一下,你想检查“/folder/subfolder/subsubfolder/test/test.txt”文件是否存在,你会做如下:

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 只是为了检查路径是否存在...

最佳答案

@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 模拟器和 Asus Zenfone 5 中尝试过,希望这会有所帮助

关于android - SAF DocumentFile - 检查路径是否存在而不在每个文件夹级别创建每个 DocumentFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966386/

相关文章:

android - 是否可以从 DocumentFile 获取常规文件?

android - 优化 Android 中 ImageView 之间的分页?

android - android中两个应用程序之间的数据共享

android - AppBarLayout 更改其中某些 View 的可见性时的奇怪行为

android - 如何在 Android 11 中实现 New Storage API?

java - 存储访问框架 - 保存 Uri

android - 从 Firebase Analytics 检索用户属性

Android - 使用 Intent 打开音频内容 uri

android - 如何使用为 Android 5.0 (Lollipop) 提供的新 SD 卡访问 API?

android - 将 EXIF 数据写入使用 DocumentFile 类保存的图像