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

时间:2016-06-22 11:13:35

标签: android storage-access-framework documentfile

成像,你要检查" /folder/subfolder/subsubfolder/test/test.txt"文件退出,您将执行以下操作:

from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from django.shortcuts import render_to_response

@csrf_protect
def any_function(request):
    csrfContext = RequestContext(request)
    return render_to_response('htmlpage', csrfContext)

这是非常慢的,是否有更快的方法来至少检查SD卡上是否存在文件?我不想创建每个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 } 只是为了检查路径是否存在...

1 个答案:

答案 0 :(得分:5)

@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,希望这将有所帮助