无法访问原始文件夹中的文件
Can't access file in the raw folder
我是 Android 开发的新手。我在 res\raw
文件夹中有一个 test.txt
文件。出于某种原因,我无法访问它。
这是我用来测试的代码。怎么会file.exists()
returnsfalse
?
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.
顺便说一句,我需要获取文件的Uri
。我需要它才能使用接受 Uri
作为参数的现有函数。
How come file.exists() returns false?
首先,资源是您开发机器上的一个文件。它不是设备上的文件。
其次,getPath()
on Uri
只是 returns Uri
的路径部分。在您的情况下,即 /raw/test.txt
。如果 Uri
是您问题的 https
URL,则路径将为 /questions/56090894/cant-access-file-in-the-raw-folder
。这些都不是任何 Android 设备上的有效文件系统路径。您不能将 semi-random 字符串传递给 File
构造函数,并期望它们有意义。
I need to get the Uri of the file
如果你真的是"get a Uri
for the resource",欢迎你试试你的uri
。 android.resource
方案有点晦涩,因此您正在使用的功能很可能不支持它。
在这种情况下,您需要:
- 在原始资源上打开
InputStream
(在 Context
上打开 getResources().openRawResource()
)
- 在您控制的某个文件上打开
FileOutputStream
(例如,在 getCacheDir()
中)
- 将字节从
InputStream
复制到 OutputStream
- 尝试
Uri.fromFile()
为图书馆创建一个Uri
也有可能该函数需要某种其他类型的 Uri
。由于我们不知道这是什么功能,因此我们无法查看其文档(如果有的话)并告诉您它可能会或可能不会期待什么。
我是 Android 开发的新手。我在 res\raw
文件夹中有一个 test.txt
文件。出于某种原因,我无法访问它。
这是我用来测试的代码。怎么会file.exists()
returnsfalse
?
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.
顺便说一句,我需要获取文件的Uri
。我需要它才能使用接受 Uri
作为参数的现有函数。
How come file.exists() returns false?
首先,资源是您开发机器上的一个文件。它不是设备上的文件。
其次,getPath()
on Uri
只是 returns Uri
的路径部分。在您的情况下,即 /raw/test.txt
。如果 Uri
是您问题的 https
URL,则路径将为 /questions/56090894/cant-access-file-in-the-raw-folder
。这些都不是任何 Android 设备上的有效文件系统路径。您不能将 semi-random 字符串传递给 File
构造函数,并期望它们有意义。
I need to get the Uri of the file
如果你真的是"get a Uri
for the resource",欢迎你试试你的uri
。 android.resource
方案有点晦涩,因此您正在使用的功能很可能不支持它。
在这种情况下,您需要:
- 在原始资源上打开
InputStream
(在Context
上打开getResources().openRawResource()
) - 在您控制的某个文件上打开
FileOutputStream
(例如,在getCacheDir()
中) - 将字节从
InputStream
复制到OutputStream
- 尝试
Uri.fromFile()
为图书馆创建一个Uri
也有可能该函数需要某种其他类型的 Uri
。由于我们不知道这是什么功能,因此我们无法查看其文档(如果有的话)并告诉您它可能会或可能不会期待什么。