Skip to content

Instantly share code, notes, and snippets.

@mhasby
Created November 15, 2016 07:06
Show Gist options
  • Save mhasby/026f02b33fcc4207b302a60645f6e217 to your computer and use it in GitHub Desktop.
Save mhasby/026f02b33fcc4207b302a60645f6e217 to your computer and use it in GitHub Desktop.
[ANDROID] copy files from 'assets' folder to sdcard
import android.content.Context;
import android.content.res.AssetManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyAssets {
public static void copyAssets(Context context) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(context.getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
}
}
if (out != null) {
try {
out.flush();
out.close();
out = null;
} catch (IOException e) {
}
}
}
}
}
public static 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);
}
}
}
@singhshantanu1996
Copy link

in = assetManager.open(filename);

File outFile = new File(context.getExternalFilesDir(null), filename);

out = new FileOutputStream(outFile);
This line has an issue, here you are fetching the internal directory of the application and not the internal storage of the android device.
The following code should work.
in = assetManager.open(filename);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/www/resources/" + filename);

the part in the quotes is the locations of the directory where you want to paste the files from the assets folder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment