6

Imaging, you want to check if "/folder/subfolder/subsubfolder/test/test.txt" file exits, you would do following:

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
}

This is very slow, is there a faster way to at least check if a file is existing on the sd card? I don't want to create each DocumentFile just for checking if a path is existing...

prom85
  • 16,896
  • 17
  • 122
  • 242

2 Answers2

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

I am not an expert and I do not know if this will work on most android, but I've tried in the Android emulator and Asus Zenfone 5, hopefully this will help

Haryanto
  • 609
  • 9
  • 17
0

Couldnt you just use

String Muri = uri.toString();

Then use shared preference for each folder uri, then call on it when needed.

J. M.
  • 115
  • 6