Using SAF, how to check if a file already exists

from the CommonsWare Community archives

At May 5, 2020, 7:47am, Shahood asked:

Hi, in my app, I have a Fragment that shows a list of available files to download. User clicks on any file to download and view its contents. However, I want to implement it such that if the file is already available in the selected directory, it is not downloaded again, only its contents are then shown to the user.

Following is the workflow I came up with:

I planned to achieve this using Storage Access Framework and I could figure out all steps but this one: Check (by filename, e.g., my_file.pdf) if required file already exists.

I simply don’t know how to create a content Uri with the help of the persisted directory Uri and a filename. If I don’t perform this check, there would be numerous copies of the same document at the end of the day PLUS undue downloading cost, which is not desirable.

Thanking in anticipation!


At May 5, 2020, 11:02am, mmurphy replied:

If you downloaded the file, you already had such a content Uri at that time, and you could persist that value (after having taken persistent permissions for its content). Then, to see if it exists, call DocumentTree.fromSingleUri(), passing in that Uri, and call exists() to see if it exists.

Alternatively, use DocumentFile.fromTreeUri() on the “directory” Uri, then use findFile() to see if there is a “file” whose display name matches your desired name.


At May 5, 2020, 11:40am, Shahood replied:

In one of your blog posts on SAF, I’ve read that display name may not be the filename we expect, e.g., my_filename.pdf; it may be something very different…so I was skeptic about even trying this solution out.
So would the display name really match with the filename using this method?


At May 5, 2020, 11:56am, mmurphy replied:

If you are the one creating the document (via your download operation), you are the one initially supplying the display name. Ideally, whatever document provider the user chose will honor your requested display name and maintain it.

This is not guaranteed, though:

A safer solution is to persist the Uri that you used when creating the document. That too is not an absolute guarantee, but it should be less fragile than relying on the display name.


At May 5, 2020, 5:07pm, Shahood replied:

It worked and I have decided to stick to it until any error comes up. Thanks for ur help!


At May 7, 2020, 2:59pm, Jan replied:

In my experience, the _ is frequently substituted when I download from google drive. Check those special characters.