Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file from res/raw by name

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"); 

The command

ddd.exists();  

yields FALSE. So this method does not work.

Trying

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

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

Simply using

R.raw.example 

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

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

like image 433
Bernd Avatar asked Apr 09 '13 21:04

Bernd


People also ask

Where is the raw folder on Android?

The raw folder is created inside the res folder: main/res/raw.

How to create folder in res in Android studio?

Step 1: Right click on res. Step 2: Then go to New. Step 3: Then go to Folder. Step 4: Then go to Res Folder Option and select.


1 Answers

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())); 
like image 200
Bernd Avatar answered Sep 23 '22 02:09

Bernd