How to check whether a known uri file exists in Android storage?

DocumentFile sourceFile = DocumentFile.fromSingleUri(context, uri);
boolean bool = sourceFile.exists();

Check if a file of a path exists like this:

File file = new File("/mnt/sdcard/Download/AppSearch_2213333_60.apk" );
if (file.exists()) {
 //Do something
}

Keep in mind to remove something like "file://" etc. otherwise use:

 File file = new File(URI.create("file:///mnt/sdcard/Download/AppSearch_2213333_60.apk").getPath());
 if (file.exists()) {
  //Do something
 }

Also you have to set proper permissions for your app in the AndroidManifest.xml to access the sdcard:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I might be a little late to the party here, but I was looking for a solution to a similar problem and was finally able to find a solution for all possible edge cases. The solution is a follows:

boolean bool = false;
        if(null != uri) {
            try {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);
                inputStream.close();
                bool = true;
            } catch (Exception e) {
                Log.w(MY_TAG, "File corresponding to the uri does not exist " + uri.toString());
            }
        }

If the file corresponding to the URI exists, then you will have an input stream object to work with, else an exception will be thrown.

Do not forget to close the input stream if the file does exist.

NOTE:

DocumentFile sourceFile = DocumentFile.fromSingleUri(context, uri);
boolean bool = sourceFile.exists();

does handle most edge cases, but what I found out was that if a file is created programmatically and stored in some folder, the user then visits the folder and manually deletes the file (while the app is running), DocumentFile.fromSingleUri wrongly says that the file exists.

Tags:

Java

Android