2016-06-22 24 views
3

イメージングで各DocumentFileを作成することなく存在している場合、あなたは「/folder/subfolder/subsubfolder/test/test.txt」ファイル終了かどうかを確認したい、あなたは次の操作を行いますチェック:SAF DocumentFile - パスは、各フォルダレベル

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カードに存在するかどうかを確認する方法はありますか?私は専門家ではないですし、これはほとんどのAndroid上で動作する場合、私は知らないが、私が試した

+0

解決方法があれば教えてください。 – Haryanto

+0

私の質問に投稿されたものよりも良いものはありません... – prom85

答えて

2
@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"); 
    } 
} 

...ただパスが存在しているかどうかをチェックするために、各DocumentFileを作成する必要はありませんAndroidエミュレータとAsus Zenfone 5では、これがうまくいけば

+0

great solution man – meysam

関連する問題