2

i'm trying to get the URI of a file in the raw folder of my app in this way:

Uri myUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myfile);

or

Uri myUri = Uri.parse("android.resource://mypackage/raw/myfile");

Then i use this method to check if the uri was correct:

File f = new File(myUri.toString());
    if (f.exists()) {
        Log.d("YES", "file exist");
    }
    if (!f.exists()){
        Log.d("NO", "file doesn't exist");
    }

But i always get: "No, file doesn't exist".

Do you know why?

Giuseppedes
  • 129
  • 9

1 Answers1

2

First, because there is no file. Resources are files on your developer machine. They are not files on the device.

Second, because new File(myUri.toString()) will never work. A Uri always has a scheme; filesystem paths never have a scheme.

Third, because even if you used new File(myUri.getPath()), that will work at most for a file:// Uri. There are many other types of Uri schemes; none of them will have paths that map directly to filesystem paths. Even with a file:// Uri, the filesystem path may not be one that you have direct access to (e.g., an arbitrary path on removable media on Android 4.4+).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Is there a way to check if the uri was correct, though? It's obviously what he wants to know, even if he didn't explicitly ask. – blimpse Apr 04 '23 at 16:50
  • 1
    @blimpse: "Is there a way to check if the uri was correct, though?" -- use `ContentResolver` and `openInputStream()` and see if it works. If you get an exception, the `Uri` was invalid. – CommonsWare Apr 04 '23 at 20:22