10

I have a jar file for which i need to pass file object. How can i pass resource or assets to that method as a file object?

How to convert assets or raw files in the project folders in to file objects ?

Pavandroid
  • 1,586
  • 2
  • 15
  • 30

2 Answers2

5

Here is what I did:

Copy Your asset file into SDCard:

AssetManager assetManager = context.getResources().getAssets();

String[] files = null;

try {
    files = assetManager.list("ringtone"); //ringtone is folder name
} catch (Exception e) {
    Log.e(LOG_TAG, "ERROR: " + e.toString());
}

for (int i = 0; i < files.length; i++) {
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open("ringtone/" + files[i]);
        out = new FileOutputStream(basepath + "/ringtone/" + files[i]);

        byte[] buffer = new byte[65536 * 2];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        Log.d(LOG_TAG, "Ringtone File Copied in SD Card");
    } catch (Exception e) {
        Log.e(LOG_TAG, "ERROR: " + e.toString());
    }
}

Then read your file by the path:

File ringFile = new File(Environment.getExternalStorageDirectory().toString() + "/ringtone", "fileName.mp3");

There you go. You have a copy of file object of your asset file. Hope this helps.

drulabs
  • 3,071
  • 28
  • 35
  • I am getting Out of Memory in my application if i did like this. – Pavandroid Jun 07 '12 at 11:38
  • This is working for me. I omitted some part. Please create the folder using mkdirs() method of file object before this code. You can google it. – drulabs Jun 07 '12 at 11:41
  • You are getting out of memory exception for @vipul's and my solutions... can you paste the logcat entries. something is not right. you testing on device or emulator? – drulabs Jun 07 '12 at 11:46
0

I'm not aware of any way to get an actual File object, but if you can work with a FileDescriptor, you could do:

FileDescriptor fd = getAssets().openFd(assetFileName).getFileDescriptor();
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109