i have some images should be displayed in the Application, the Q. is how to copy the images i am putting in the assets folder in the code to a folder under the SC card of the user on install the application on the phone
Asked
Active
Viewed 2,040 times
2 Answers
2
Try with this,
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
out = new FileOutputStream("/sdcard/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Don't forget to add this permission in your manifiest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Aerrow
- 12,086
- 10
- 56
- 90
-
it your application's assets folder. – Aerrow Aug 29 '12 at 08:47
-
how can i check if this is the first time the user run the application as i don wanna every time the copy happened ?! – omnia Mm Aug 29 '12 at 08:59
-
check your sdCard folder length, if it's empty means you will copy otherwise you won't – Aerrow Aug 29 '12 at 09:06
-
out = new FileOutputStream("/sdcard/" + filename); ,, an error occured "the file is not exist" – omnia Mm Aug 29 '12 at 10:02
-
1First of all create the directory to move the images. then user out = new FileOutputStream("/sdcard/Your_Folder" + filename); – Aerrow Aug 29 '12 at 10:09
0
So I needed to do something similar except for all files, and on boot for an AOSP package. Here is a link to the package if anyone is interested (see AssetCopyReceiver.java).
This will copy all files under sdcard to their respective locations and it should also work with subdirectories. It works as an on boot receiver which won't work for a regular app, so it will need to be modified but the code is the same. It is heavily based on the first answer as I started from there, and corrected some issues that I found as I needed to extend it.

Andrew T.
- 4,598
- 4
- 35
- 54