Skip to main content

Android: How to copy files in "assets" to sdcard?



I have a few files in the assets folder. I need to copy all of them to a folder say /sdcard/folder. I want to do this from within a thread. How do I do it?





Source: Tips4all

Comments

  1. If anyone else is having the same problem, this is how I did it

    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);
    }
    }


    Reference : Move file using Java - http://www.java2s.com/Code/Java/File-Input-Output/MoveaFile.htm

    ReplyDelete
  2. Based on your solution, I did something of my own to allow subfolders. Someone might find this helpful:

    ...

    copyFileOrDir("myrootdir");


    ...

    private void copyFileOrDir(String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
    assets = assetManager.list(path);
    if (assets.length == 0) {
    copyFile(path);
    } else {
    String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
    File dir = new File(fullPath);
    if (!dir.exists())
    dir.mkdir();
    for (int i = 0; i < assets.length; ++i) {
    copyFileOrDir(path + "/" + assets[i]);
    }
    }
    } catch (IOException ex) {
    Log.e("tag", "I/O Exception", ex);
    }
    }

    private void copyFile(String filename) {
    AssetManager assetManager = this.getAssets();

    InputStream in = null;
    OutputStream out = null;
    try {
    in = assetManager.open(filename);
    String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
    out = new FileOutputStream(newFileName);

    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
    out.write(buffer, 0, read);
    }
    in.close();
    in = null;
    out.flush();
    out.close();
    out = null;
    } catch (Exception e) {
    Log.e("tag", e.getMessage());
    }

    }

    ReplyDelete
  3. Good example. Answered my question of how to access files in the assets folder.

    Only change I would suggest is in the for loop. The following format would work too and is preferred:

    for(String filename : files) {
    InputStream in = null;
    OutputStream out = null;
    try {
    in = assetManager.open(filename);
    out = new FileOutputStream("/sdcard/" + filename);
    ...
    }

    ReplyDelete
  4. Use AssetManager, it allows to read the files in the assets. Then use regular Java IO to write the files to sdcard.

    Google is your friend, here's an example.

    ReplyDelete
  5. The solution above did not work due to some errors:


    directory creation did not work
    assets returned by Android contain also three folders: images, sounds and webkit
    Added way to deal with large files: Add extension .mp3 to the file in the assets folder in your project and during copy the target file will be without the .mp3 extension


    Here is the code (I left the Log statements but you can drop them now):

    final static String TARGET_BASE_PATH = "/sdcard/appname/voices/";

    private void copyFilesToSdCard() {
    copyFileOrDir(""); // copy all files in assets folder in my project
    }

    private void copyFileOrDir(String path) {
    AssetManager assetManager = this.getAssets();
    String assets[] = null;
    try {
    Log.i("tag", "copyFileOrDir() "+path);
    assets = assetManager.list(path);
    if (assets.length == 0) {
    copyFile(path);
    } else {
    String fullPath = TARGET_BASE_PATH + path;
    Log.i("tag", "path="+fullPath);
    File dir = new File(fullPath);
    if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
    if (!dir.mkdirs());
    Log.i("tag", "could not create dir "+fullPath);
    for (int i = 0; i < assets.length; ++i) {
    String p;
    if (path.equals(""))
    p = "";
    else
    p = path + "/";

    if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
    copyFileOrDir( p + assets[i]);
    }
    }
    } catch (IOException ex) {
    Log.e("tag", "I/O Exception", ex);
    }
    }

    private void copyFile(String filename) {
    AssetManager assetManager = this.getAssets();

    InputStream in = null;
    OutputStream out = null;
    String newFileName = null;
    try {
    Log.i("tag", "copyFile() "+filename);
    in = assetManager.open(filename);
    if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
    newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
    else
    newFileName = TARGET_BASE_PATH + filename;
    out = new FileOutputStream(newFileName);

    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
    out.write(buffer, 0, read);
    }
    in.close();
    in = null;
    out.flush();
    out.close();
    out = null;
    } catch (Exception e) {
    Log.e("tag", "Exception in copyFile() of "+newFileName);
    Log.e("tag", "Exception in copyFile() "+e.toString());
    }

    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.