如何阅读RES /原始的名字文件原始、名字、文件、RES

2023-09-11 20:24:26 作者:公主加屌丝等于我i

我想打开从文件夹RES /生/文件。 我绝对相信该文件存在。 要打开我试图文件

I want to open a file from the folder res/raw/. I am absolutely sure that the file exists. To open the file I have tried

File ddd = new File("res/raw/example.png");

命令

ddd.exists(); 

生成FALSE。因此,这种方法是行不通的。

yields FALSE. So this method does not work.

尝试

MyContext.getAssets().open("example.png");

结束了在一个例外的getMessage()空。

ends up in an exception with getMessage() "null".

只需用

R.raw.example

是不可能的,因为文件名是运行作为字符串中唯一已知的。

is not possible because the filename is only known during runtime as a string.

为什么如此难以访问的文件夹/ RES /生/?

Why is it so difficult to access a file in the folder /res/raw/ ?

推荐答案

在给定的链接,我能够解决自己的问题的帮助。正确的方法是,以获得与资源ID

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("raw/FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

要得到它作为一个的InputStream

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("raw/FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));