如何通过名称从 res/raw 读取文件

我要从文件夹 未加工的/未经加工的/中打开一个文件。 我绝对确定文件存在。 打开我试过的文件

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

命令

ddd.exists();

所以这个方法不起作用。

正在努力

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

以 getMessage ()“ null”异常结束。

简单的使用

R.raw.example

是不可能的,因为文件名仅在运行时作为字符串被知道。

为什么访问/res/raw/文件夹中的文件如此困难?

163767 次浏览

Here is example of taking XML file from raw folder:

 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

Then you can:

 String sxml = readTextFile(XmlFileInputStream);

when:

 public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();


byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {


}
return outputStream.toString();
}

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("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName());

To get it as a InputStream

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

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Here are two approaches you can read raw resources using Kotlin.

You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.

Cheers mate 🎉

// R.raw.data_post


this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)