openRawResourceFd fails on android

WOPR picture WOPR · Nov 22, 2011 · Viewed 8.6k times · Source

I'm writing my first Android application, and I'm trying to read a res/raw resource file.

The following code throws a FileNotFound Exception:

AssetFileDescriptor fd = res.openRawResourceFd(R.raw.myfile);

but this line of code works:

InputStream stream = res.openRawResource (R.raw.myfile);

I need the AssetFileDescriptor in order to determine the length of the file. Any ideas why it isn't working?

Answer

Chepech picture Chepech · Jan 22, 2014

You can do it this way:

FileDescriptor fd = getResources().openRawResourceFd(R.raw.rawResourceId).getFileDescriptor();

No try/catch block required.