Bernd
Bernd

Reputation: 3565

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/ ?

Upvotes: 107

Views: 178855

Answers (6)

Evin1_
Evin1_

Reputation: 12906

Expanding a bit on the above answers, you can use the bufferedReader extension to get the value as a string.


If you don't have the resource identifier, you can use (discouraged):

val identifier = resources.getIdentifier("filename", "raw", context.packageName)
val rawString = resources.openRawResource(identifier)
  .bufferedReader()
  .use { it.readText() }

Or, if you have the resource identifier:

val rawString = resources.openRawResource(R.raw.identifier_name)
  .bufferedReader()
  .use { it.readText() }

Upvotes: 1

Ramakrishna Joshi
Ramakrishna Joshi

Reputation: 1578

We need to pass the raw file id and open and close input stream to convert the raw resource.

import android.content.Context;
import android.content.res.Resources;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtils {
    public static File getFileFromRaw(Context context, int resId, String fileName) {
        Resources resources = context.getResources();
        File file = null;
        try {
            // Open the audio file from the raw folder
            InputStream inputStream = resources.openRawResource(resId);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            inputStream.close();

            // Create a new File Object
            file = new File(context.getExternalFilesDir(null), fileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}

and use it like this

File audioFile = FileUtils.getFileFromRaw(this, R.raw.rain_drops, "rain_drops.m4a");

Upvotes: 0

Morgan Koh
Morgan Koh

Reputation: 2475

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)

Upvotes: 7

Bernd
Bernd

Reputation: 3565

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

Upvotes: 183

user2574545
user2574545

Reputation: 161

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.

Upvotes: 16

Emil Adz
Emil Adz

Reputation: 41139

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();
    }

Upvotes: 53

Related Questions