7

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?

Vivek Kalkur
  • 2,200
  • 2
  • 21
  • 40
WOPR
  • 319
  • 2
  • 6
  • 14

3 Answers3

5

You can do it this way:

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

No try/catch block required.

Chepech
  • 5,258
  • 4
  • 47
  • 70
1

This works;

AssetFileDescriptor afd = res.openRawResourceFd(R.raw.rawResourceId);
Jessicardo
  • 826
  • 1
  • 8
  • 12
0

Move your myfile to asset folder and try this

try{
    AssetFileDescriptor descriptor = getAssets().openFd( "myfile" );
    FileDescriptor fd = descriptor.getFileDescriptor();
}
catch(Exception)
{

}

Or you can try to open a RAW file from the resources/raw foder with this code:

FileDescriptor fd = getResources().openRawResourceFd(R.raw.myfile).getFileDescriptor();
xarlymg89
  • 2,552
  • 2
  • 27
  • 41
Pawan
  • 1,503
  • 2
  • 19
  • 28
  • 1
    This is not the permanent solution, as in asset folder i am getting file is compressed error for which i need to put file in raw directory only see this thread http://stackoverflow.com/questions/6186866/java-io-filenotfoundexception-this-file-can-not-be-opened-as-a-file-descriptor – Shridutt Kothari Jun 09 '15 at 16:03
  • openRawResource returns Inputstream and not FileInputStream – ozmank Feb 11 '16 at 08:42