60

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

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

peterh
  • 11,875
  • 18
  • 85
  • 108
Arkaha
  • 1,582
  • 3
  • 17
  • 19
  • 21
    There is a huge difference between programming for android and J2ME – Janusz May 18 '10 at 11:05
  • 3
    It's funny to read such a comment on a question about something that works identically on Android and J2ME. See my answer. – 0xF Feb 04 '14 at 22:17

8 Answers8

135

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

Samuh
  • 36,316
  • 26
  • 109
  • 116
  • 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? – Arkaha May 18 '10 at 16:03
  • what do you mean by non-standard XML? You can bundle XML files in assets also. – Samuh May 18 '10 at 16:26
  • 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.. – Arkaha May 18 '10 at 18:50
  • Files in res/raw are not processed in any way by the resource compiler, so will not generate errors because of their content. – hackbod May 19 '10 at 01:30
  • @hackbod 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. – Snicolas Jan 20 '12 at 07:57
  • 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? – Guy Oct 10 '12 at 14:42
  • 1
    @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. – m0skit0 Nov 16 '12 at 11:25
  • 10 years later and this answer is still relevant. – Danish Ansari Nov 20 '20 at 06:14
26
InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
Lucifer
  • 29,392
  • 25
  • 90
  • 143
Adrian Vintu
  • 396
  • 2
  • 2
  • 20
    Please see the answer by Samuh (below), it is more accurate. – BoD Oct 13 '11 at 12:14
  • 1
    As a side note, raw folder does not allow access by filename. Some apps need dynamic filenames so in such cases `assets` folder is useful – Caner Nov 29 '11 at 11:10
  • 10
    he didn't ask about assets/ he asked about res/raw/ – Jeffrey Blattman Feb 16 '12 at 17:54
  • 2
    This is not the way to do it in Android. Check Samuh answer. – m0skit0 Nov 16 '12 at 11:24
  • 2
    He said res folder, not assets folder. – Barry Fruitman Feb 13 '13 at 23:54
  • 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) – vpathak Dec 01 '13 at 00:53
  • How would I write this in Kotlin? ``val raw = context.getAssets().open("$resFileName.mp3")`` is not working for me. – Martin Erlic Sep 05 '18 at 03:14
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);
Flexo
  • 87,323
  • 22
  • 191
  • 272
sravan
  • 5,303
  • 1
  • 31
  • 33
  • 6
    This line: int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName()); is GOLD – Radu Apr 27 '14 at 11:56
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() }
}
yoAlex5
  • 29,217
  • 8
  • 193
  • 205
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!!

Lucifer
  • 29,392
  • 25
  • 90
  • 143
poojan9118
  • 2,373
  • 2
  • 17
  • 13
5

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.

0xF
  • 3,214
  • 1
  • 25
  • 29
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.

java dev
  • 1,044
  • 1
  • 11
  • 17
-1

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

IgniteCoders
  • 4,834
  • 3
  • 44
  • 62