[英]Can't access file in the raw folder
I'm new to Android development. 我是Android开发的新手。 I have a
test.txt
file in the res\\raw
folder. 我在
res\\raw
文件夹中有一个test.txt
文件。 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
? 为什么
file.exists()
返回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. 顺便说一句,我需要获取文件的
Uri
。 I need that in order to be able to use an existing function that accepts a Uri
as an argument. 我需要它,以便能够使用接受
Uri
作为参数的现有函数。
How come file.exists() returns false?
为什么file.exists()返回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
. 第二,
getPath()
上Uri
只是返回的路径部分Uri
。 In your case, that is /raw/test.txt
. 您的情况是
/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
. 如果
Uri
是您问题的https
URL,则路径为/questions/56090894/cant-access-file-in-the-raw-folder
。 Neither of those would be valid filesystem paths on any Android device. 这些都不是任何Android设备上的有效文件系统路径。 You cannot take semi-random strings, pass them to the
File
constructor, and expect them to have meaning. 您不能采用半随机字符串,将它们传递给
File
构造函数,并期望它们具有含义。
I need to get the Uri of the file
我需要获取文件的Uri
If you really mean "get a Uri
for the resource", you are welcome to try your uri
. 如果您确实要说“获取资源的
Uri
”,欢迎尝试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. android.resource
方案有点晦涩难懂,因此很有可能您使用的函数将不支持它。
In that case, you will need to: 在这种情况下,您将需要:
InputStream
on your raw resource ( getResources().openRawResource()
on a Context
) InputStream
getResources().openRawResource()
在Context
上的getResources().openRawResource()
) FileOutputStream
on some file that you control (eg, in getCacheDir()
) FileOutputStream
(例如,在getCacheDir()
) InputStream
to the OutputStream
InputStream
复制到OutputStream
Uri.fromFile()
to create a Uri
for the library Uri.fromFile()
为该库创建一个Uri
It is also possible that the function is expecting some other sort of Uri
. 该函数还可能期望其他类型的
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. 由于我们不知道它是什么功能,因此我们无法查看其文档(如果有的话)并告诉您它可能会或可能不会期望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.