Issue
I'm new to Android development. I have a test.txt
file in the res\raw
folder. For some reason, I'm not able to access it.
Here's the code I'm using just to test. How come file.exists()
returns false
?
final String path = "android.resource://" + getActivity().getPackageName() + "/raw/test.txt";
final Uri uri = Uri.parse(path);
final File file = new File(uri.getPath());
boolean exists = file.exists(); // Returns false.
By the way, I need to get the Uri
of the file. I need that in order to be able to use an existing function that accepts a Uri
as an argument.
Solution
How come file.exists() returns false?
First, a resource is a file on your development machine. It is not a file on the device.
Second, getPath()
on Uri
simply returns the path portion of the Uri
. In your case, that is /raw/test.txt
. If the Uri
were the https
URL of your question, the path would be /questions/56090894/cant-access-file-in-the-raw-folder
. Neither of those would be valid filesystem paths on any Android device. You cannot take semi-random strings, pass them to the File
constructor, and expect them to have meaning.
I need to get the Uri of the file
If you really mean "get a Uri
for the resource", you are welcome to try your uri
. The android.resource
scheme is a bit obscure, and so there is a good chance that the function that you are using will not support it.
In that case, you will need to:
- Open an
InputStream
on your raw resource (getResources().openRawResource()
on aContext
) - Open a
FileOutputStream
on some file that you control (e.g., ingetCacheDir()
) - Copy the bytes from the
InputStream
to theOutputStream
- Try
Uri.fromFile()
to create aUri
for the library
It is also possible that the function is expecting some other sort of Uri
. Since we do not know what function this is, we cannot review its documentation (if it has any) and tell you what it may or may not be expecting.
Answered By - CommonsWare
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.