How to read file from res/raw by name
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.