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

The file uri is known, such as

`file:///mnt/sdcard/Download/AppSearch_2213333_60.apk`

I want to check if this file can open or not in background, how to do?



Solution 1:[1]

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" />

Solution 2:[2]

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

Solution 3:[3]

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.

Solution 4:[4]

Start by extracting the filename using URI:

final String path = URI.create("file:///mnt/sdcard/Download/AppSearch_2213333_60.apk")
    .getPath(); // returns the path segment of this URI, ie the file path
final File file = new File(path).getCanonicalFile();
// check if file.exists(); try and check if .canRead(), etc

It is advisable to use URI here, since it will take care of decoding all possible spaces/characters illegal in URIs, but legal in file names.

Solution 5:[5]

Above answers will not work for all versions of Android (see Get filename and path from URI from mediastore and Get real path from URI, Android KitKat new storage access framework), but there is an easy way using DocumentsContract:

DocumentsContract.isDocumentUri(context,myUri)

Solution 6:[6]

I wrote a function that checks if a file exists on a given path. The path might me absolute path or Uri path.

fun localFileExist(localPathOrUri: String?, context:Context): Boolean {
    if (localPathOrUri.isNullOrEmpty()) {
        return false
    }

    var exists = File(localPathOrUri).exists()
    if (exists) {
        return exists
    }

    val cR = context.getContentResolver()
    val uri = Uri.parse(localPathOrUri)

    try {
        val inputStream = cR.openInputStream(uri)
        if (inputStream != null) {
            inputStream.close()
            return true
        }
    } catch (e: java.lang.Exception) {
        //file not exists
    }
    return exists
}

Solution 7:[7]

import java.nio.file.Paths;
import java.nio.file.Files;

boolean exists = Files.exists(Paths.get(URI));

Much more concise..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alex
Solution 2 David Buck
Solution 3 mang4521
Solution 4 fge
Solution 5
Solution 6 Sirojiddin Komolov
Solution 7 dnim