Reading assets or raw or resource files as a File object in Android
Solution 1
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.
Solution 2
To Read raw files into File.
InputStream ins = getResources().openRawResource(R.raw.my_db_file);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
int size = 0;
// Read the entire resource into a local byte buffer.
byte[] buffer = new byte[1024];
while((size=ins.read(buffer,0,1024))>=0){
outputStream.write(buffer,0,size);
}
ins.close();
buffer=outputStream.toByteArray();
FileOutputStream fos = new FileOutputStream("mycopy.db");
fos.write(buffer);
fos.close();
To avoid OutOfMemory apply following logic.
Don't create a huge ByteBuffer that contains ALL of the data at once. Create a much smaller ByteBuffer, fill it with data, then write this data to the FileChannel. Then reset the ByteBuffer and continue until all the data is written.
Pavandroid
Am a Java Mobile Programmer. check www.pavandroid.blogspot.com for more info....
Updated on July 20, 2022Comments
-
Pavandroid over 1 year
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 almost 12 yearsI am getting Out of Memory in my application if i did like this.
-
Pavandroid almost 12 yearsI am getting Out of Memory in my application if i did like this.
-
Pavandroid almost 12 yearsI don't know in what way this can be used. Can you explain the usage of this descriptor.
-
drulabs almost 12 yearsThis 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 almost 12 yearsYou 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?
-
Pragnesh Ghoda シ over 7 yearsThanks for the solution. +1 for you. Cheers.