How to read a file from res / raw by name

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

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

Team

 ddd.exists(); 

gives a FALSE . Therefore, this method does not work.

Attempt

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

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

Just using

 R.raw.example 

impossible because the file name is known only at run time as a string.

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

+58
android file-io resources
Apr 09 '13 at 21:24
source share
4 answers

Using these links, I was able to solve the problem myself. The correct way is to get the resource identifier using

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

To get it as an InputStream

 InputStream ins = getResources().openRawResource( getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION", "raw", getPackageName())); 
+112
Apr 10 '13 at 19:18
source share

Here is an example of taking an XML file from a raw folder:

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

Then you can:

  String sxml = readTextFile(XmlFileInputStream); 

if:

  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(); } 
+34
Apr 09 '13 at 21:27
source share

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

BUT there is a limitation of the IDE that the file name you use can only contain lowercase alphanumeric characters and a period. Therefore, file names such as XYZ.txt or my_data.bin will not be specified in R.

+9
Jul 11 '13 at 22:35
source share

Here are two approaches you can read with Kotlin.

You can get it by getting the resource identifier. Or you can use a string identifier in which you can programmatically change the file name in increments.

Hooray buddy 🎉

 // R.raw.data_post this.context.resources.openRawResource(R.raw.data_post) this.context.resources.getIdentifier("data_post", "raw", this.context.packageName) 
0
Feb 01 '19 at 7:26
source share



All Articles