How to get access to raw resources that I put in res folder?
Asked Answered
S

8

63

In J2ME, I've do this like that: getClass().getResourceAsStream("/raw_resources.dat");

But in android, I always get null on this, why?

Slavism answered 18/5, 2010 at 10:40 Comment(2)
There is a huge difference between programming for android and J2MEUdela
It's funny to read such a comment on a question about something that works identically on Android and J2ME. See my answer.Hartwig
F
26
InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
Fabiola answered 18/5, 2010 at 17:56 Comment(7)
Please see the answer by Samuh (below), it is more accurate.Gringo
As a side note, raw folder does not allow access by filename. Some apps need dynamic filenames so in such cases assets folder is usefulHerbage
he didn't ask about assets/ he asked about res/raw/Paramilitary
This is not the way to do it in Android. Check Samuh answer.Clef
He said res folder, not assets folder.Corinacorine
While the objections are sensible (he wants resource i.e. files with known readers and content formats and not a low level asset) - there is one case where using asset really helped. In an android test case the BitmapFactory.decode ( getContext().getResources() , R.drawable.id ) would give me null - even through the same code worked in the application. Using the low level asset helped me open the bitmap as and handle it as a byte buffer, thereby allowing to run the test correctly (even though in a hackish manner)Tletski
How would I write this in Kotlin? val raw = context.getAssets().open("$resFileName.mp3") is not working for me.Whitehouse
H
137

For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.

Heredity answered 18/5, 2010 at 10:53 Comment(8)
Samuh, thanks for your reply, if i do this, i've got errors Android XML Format Problem, because i use not standard xml, is there other way to use it as really raw data?Slavism
what do you mean by non-standard XML? You can bundle XML files in assets also.Heredity
Samuh, i'm porting j2me application, and it has files with extension *.xml, content of such files very similar to xml, but not the same, eclipse shouting on this files, because it can't compile it. probably i can set some kind of "ignore" on this files? but i don't know how..Slavism
Files in res/raw are not processed in any way by the resource compiler, so will not generate errors because of their content.Magnificat
@Magnificat but through this technique, you achieve compile tim checking of the presence of resoure files and that's a huge step forward to ensure code quality.Alkene
Hey Samuah. I have a test project X that tests project Y. Project Y has library Z as reference. library Z has a raw resource R which I'm trying to open but I keep getting resource not found. Any idea why your snippet doesn't work for this?Greenleaf
@Guy: common problem when you have different R's. You are simply not referencing the right R. Check your imports or reference the right R that has the resource.Clef
10 years later and this answer is still relevant.Bey
F
26
InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
Fabiola answered 18/5, 2010 at 17:56 Comment(7)
Please see the answer by Samuh (below), it is more accurate.Gringo
As a side note, raw folder does not allow access by filename. Some apps need dynamic filenames so in such cases assets folder is usefulHerbage
he didn't ask about assets/ he asked about res/raw/Paramilitary
This is not the way to do it in Android. Check Samuh answer.Clef
He said res folder, not assets folder.Corinacorine
While the objections are sensible (he wants resource i.e. files with known readers and content formats and not a low level asset) - there is one case where using asset really helped. In an android test case the BitmapFactory.decode ( getContext().getResources() , R.drawable.id ) would give me null - even through the same code worked in the application. Using the low level asset helped me open the bitmap as and handle it as a byte buffer, thereby allowing to run the test correctly (even though in a hackish manner)Tletski
How would I write this in Kotlin? val raw = context.getAssets().open("$resFileName.mp3") is not working for me.Whitehouse
P
16

In some situations we have to get image from drawable or raw folder using image name instead if generated id

// Image View Object 
        mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for  to Fetch  image from resourse 
Context mContext=getApplicationContext();

// getResources().getIdentifier("image_name","res_folder_name", package_name);

// find out below example 
    int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());

// now we will get contsant id for that image       
        mIv.setBackgroundResource(i);
Pugging answered 5/6, 2012 at 12:51 Comment(1)
This line: int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName()); is GOLDImagine
R
9

Android access to raw resources

An advance approach is using Kotlin Extension function

fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
    return resources.openRawResource(resourceId)
}

One more interesting thing is extension function use that is defined in Closeable scope

For example you can work with input stream in elegant way without handling Exceptions and memory managing

fun Context.readRaw(@RawRes resourceId: Int): String {
    return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
Redness answered 10/11, 2017 at 15:1 Comment(0)
C
6
TextView txtvw = (TextView)findViewById(R.id.TextView01);
        txtvw.setText(readTxt());

 private String readTxt()
    {
    InputStream raw = getResources().openRawResource(R.raw.hello);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try
    {
        i = raw.read();
        while (i != -1)
        {
            byteArrayOutputStream.write(i);
            i = raw.read();
        }
        raw.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block

        e.printStackTrace();
    }


    return byteArrayOutputStream.toString();

}

TextView01:: txtview in linearlayout hello:: .txt file in res/raw folder (u can access ny othr folder as wel)

Ist 2 lines are 2 written in onCreate() method

rest is to be written in class extending Activity!!

Cleghorn answered 2/7, 2010 at 10:15 Comment(0)
H
6

getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).

Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:

getClass().getResourcesAsStream("/assets/raw_resources.dat");

It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.

Hartwig answered 4/2, 2014 at 22:7 Comment(2)
Eyy, nice. Doesn't even need a Context.Pannonia
It should be noted that the assets folder is located as src/main/assets.Pannonia
F
3

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

Froebel answered 21/2, 2013 at 10:26 Comment(4)
openRawResource() require an int, not a string developer.android.com/reference/android/content/res/…Micheal
will this also work on resources that exist in the drawable folder?Coulee
Use "R.raw.NameOfResource" as int.Sawbuck
Even tough the method requires an int, I was able to find my file with R.raw.filename (without the extension)Motherinlaw
K
-1

This worked for for me: getResources().openRawResource(R.raw.certificate)

Karp answered 5/6, 2020 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.