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.
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:
InputStream
on your raw resource ( getResources().openRawResource()
on a Context
) FileOutputStream
on some file that you control (eg, in getCacheDir()
) InputStream
to the OutputStream
Uri.fromFile()
to create a Uri
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.