Using SAF, how to check if a file already exists

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:

  • Check (from preferences) if a download directory is already selected
  • If yes:
    • Check (by filename, e.g., my_file.pdf) if required file already exists:
      • If yes, show file contents
      • If no, download the file, save it to the selected directory and show file contents
  • If no:
    • Let the user select a download directory
    • Persist it in preferences
    • Download the file, save it to the selected directory and show file contents

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!

1 Like

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.

1 Like

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?

1 Like

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:

  • The document provider might need to change the display name (e.g., your filename has Unicode characters in it and the provider needs strict ASCII)
  • The user might rename the document

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.

1 Like

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

1 Like

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