简体   繁体   English

无法访问原始文件夹中的文件

[英]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: 在这种情况下,您将需要:

  • Open an InputStream on your raw resource ( getResources().openRawResource() on a Context ) 在原始资源上打开一个InputStream getResources().openRawResource()Context上的getResources().openRawResource()
  • Open a FileOutputStream on some file that you control (eg, in getCacheDir() ) 在您控制的某个文件上打开FileOutputStream (例如,在getCacheDir()
  • Copy the bytes from the InputStream to the OutputStream 将字节从InputStream复制到OutputStream
  • Try 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM