Copy directory from Assets to local directory
Asked Answered
A

7

23

I'm trying to use a directory that I have in my assets folder and access it as a File. Is it possible to access something in the Assets directory as a File? If not, how can I copy a directory from the Assets folder to the application's local directory?

I would copy a file like so:

    try
    {
        InputStream stream = this.getAssets().open("myFile");
        OutputStream output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/myNewFile"));

        byte data[] = new byte[1024];
        int count;

        while((count = stream.read(data)) != -1)
        {
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        stream.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

However, I'm not sure how I would be able to do this for a directory.

I would rather not build my infrastructure around something that doesn't work, so how would I copy a directory from Assets to a local directory, or is it possible to access a directory in my Assets as a File?

EDIT

This is how I solved it for my own project:

InputStream stream = null;
OutputStream output = null;

for(String fileName : this.getAssets().list("demopass"))
{
    stream = this.getAssets().open("directoryName/" + fileName);
    output = new BufferedOutputStream(new FileOutputStream(this.getFilesDir() + "/newDirectory/" + fileName));

    byte data[] = new byte[1024];
    int count;

    while((count = stream.read(data)) != -1)
    {
        output.write(data, 0, count);
    }

    output.flush();
    output.close();
    stream.close();

    stream = null;
    output = null;
}
Alewife answered 22/3, 2013 at 16:12 Comment(5)
Maybe this can help: #4447977Marylynnmarylynne
@Marylynnmarylynne I appreciate the suggestion, however, it is not the Assets directory that I want to copy, but rather a directory inside the assets folder that I want to copy.Alewife
this doesn't coppy subdirectories, does it?Vaclava
For Copy Subdirectory try this link: #4447977Quiff
For Copy Subdirectory try this link:Quiff
C
11

As suggested by dmaxi in comment above, you can use his link, with this code:

    void displayFiles (AssetManager mgr, String path) {
        try {
            String list[] = mgr.list(path);
            if (list != null)
                for (int i=0; i<list.length; ++i)
                {
                    Log.v("Assets:", path +"/"+ list[i]);
                    displayFiles(mgr, path + "/" + list[i]);
                }
        } catch (IOException e) {
             Log.v("List error:", "can't list" + path);
        }
     }

I took it on this link. Maybe you can combine this code with precedent one.

EDIT: see also AssetManager.

private void copyFolder(String name) {
            // "Name" is the name of your folder!
    AssetManager assetManager = getAssets();
    String[] files = null;

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        // Checking file on assets subfolder
        try {
            files = assetManager.list(name);
        } catch (IOException e) {
            Log.e("ERROR", "Failed to get asset file list.", e);
        }
        // Analyzing all file on assets subfolder
        for(String filename : files) {
            InputStream in = null;
            OutputStream out = null;
            // First: checking if there is already a target folder
            File folder = new File(Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name);
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }
            if (success) {
                // Moving all the files on external SD
                try {
                    in = assetManager.open(name + "/" +filename);
                    out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name + "/" + filename);
                    Log.i("WEBVIEW", Environment.getExternalStorageDirectory() + "/yourTargetFolder/" + name + "/" + filename);
                    copyFile(in, out);
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                } catch(IOException e) {
                    Log.e("ERROR", "Failed to copy asset file: " + filename, e);
                } finally {
                    // Edit 3 (after MMs comment)
                    in.close();
                    in = null;
                    out.flush();
                    out.close();
                    out = null;
                }
            }
            else {
                // Do something else on failure
            }       
        }
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
    } else {
        // Something else is wrong. It may be one of many other states, but all we need
        // is to know is we can neither read nor write
    }
}

// Method used by copyAssets() on purpose to copy a file.
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);
    }
}

EDIT 2: i'have added an example above: this piece of code copy only a specific folder from assets, to sd card. Let me know if it works!

Crim answered 22/3, 2013 at 16:51 Comment(5)
That won't help me to copy a directory, as I can only copy the files in the directory and listing all files would copy all of the files. I am hoping to copy the directory as a whole, not every file in the assets directory.Alewife
@Alewife i was too curious to find out a solution, and i have elaborated a solution, take a look on my answers! I hope it works.Crim
I think this will work. I couldn't figure out how to get the string parameter in getAssets(String) worked. I will follow up with my own solution, if I can get it to work.Alewife
You're not closing the stream if there's a fail (use a finally block!)Liba
Thumbsup ;) I still think that out could be null and if you get a NPE you won't be closing it, but I'm not sure.Liba
E
5

Here is a recursive function to do this - copyAssetFolder.

public static boolean copyAssetFolder(Context context, String srcName, String dstName) {
    try {
        boolean result = true;
        String fileList[] = context.getAssets().list(srcName);
        if (fileList == null) return false;

        if (fileList.length == 0) {
            result = copyAssetFile(context, srcName, dstName);
        } else {
            File file = new File(dstName);
            result = file.mkdirs();
            for (String filename : fileList) {
                result &= copyAssetFolder(context, srcName + File.separator + filename, dstName + File.separator + filename);
            }
        }
        return result;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

public static boolean copyAssetFile(Context context, String srcName, String dstName) {
    try {
        InputStream in = context.getAssets().open(srcName);
        File outFile = new File(dstName);
        OutputStream out = new FileOutputStream(outFile);
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Or the same in Kotlin

fun AssetManager.copyAssetFolder(srcName: String, dstName: String): Boolean {
    return try {
        var result = true
        val fileList = this.list(srcName) ?: return false
        if (fileList.isEmpty()) {
            result = copyAssetFile(srcName, dstName)
        } else {
            val file = File(dstName)
            result = file.mkdirs()
            for (filename in fileList) {
                result = result and copyAssetFolder(
                    srcName + separator.toString() + filename,
                    dstName + separator.toString() + filename
                )
            }
        }
        result
    } catch (e: IOException) {
        e.printStackTrace()
        false
    }
}

fun AssetManager.copyAssetFile(srcName: String, dstName: String): Boolean {
    return try {
        val inStream = this.open(srcName)
        val outFile = File(dstName)
        val out: OutputStream = FileOutputStream(outFile)
        val buffer = ByteArray(1024)
        var read: Int
        while (inStream.read(buffer).also { read = it } != -1) {
            out.write(buffer, 0, read)
        }
        inStream.close()
        out.close()
        true
    } catch (e: IOException) {
        e.printStackTrace()
        false
    }
}
Eventuality answered 15/3, 2019 at 13:38 Comment(0)
A
2

You can use following method for copying your asset folder to a location in your SD Card. From your calling method just call moveAssetToStorageDir("") for moving entire asset folder. In case of sub folders you can specify the relative path inside the asset folder.

public void moveAssetToStorageDir(String path){
    File file = getExternalFilesDir(null);
    String rootPath = file.getPath() + "/" + path;
    try{
        String [] paths = getAssets().list(path);
        for(int i=0; i<paths.length; i++){
            if(paths[i].indexOf(".")==-1){
                File dir = new File(rootPath + paths[i]);
                dir.mkdir();
                moveAssetToStorageDir(paths[i]);
            }else {
                File dest = null;
                InputStream in = null;
                if(path.length() == 0) {
                    dest = new File(rootPath + paths[i]);
                    in = getAssets().open(paths[i]);
                }else{
                    dest = new File(rootPath + "/" + paths[i]);
                    in = getAssets().open(path + "/" + paths[i]);
                }
                dest.createNewFile();
                FileOutputStream out = new FileOutputStream(dest);
                byte [] buff = new byte[in.available()];
                in.read(buff);
                out.write(buff);
                out.close();
                in.close();
            }
        }
    }catch (Exception exp){
        exp.printStackTrace();
    }
}
Arluene answered 7/1, 2016 at 6:9 Comment(0)
S
2

Here is the clean version of the OP's answer.

public void copyAssetFolderToFolder(Context activity, String assetsFolder, File destinationFolder) {
  InputStream stream = null;
  OutputStream output = null;
  try {
    for (String fileName : activity.getAssets().list(assetsFolder)) {
      stream = activity.getAssets().open(assetsFolder + ((assetsFolder.endsWith(File.pathSeparator))?"":File.pathSeparator) + fileName);
      output = new BufferedOutputStream(new FileOutputStream(new File(destinationFolder, fileName)));

      byte data[] = new byte[1024];
      int count;

      while ((count = stream.read(data)) != -1) {
        output.write(data, 0, count);
      }

      output.flush();
      output.close();
      stream.close();

      stream = null;
      output = null;
    }
  } catch (/*any*/Exception e){e.printStackTrace();}
}

For future reference, please save everyone the trouble and post contextually complete source listings. This site can be a great coding resource for beginners and experts, if only you would post complete answers. One cannot assume that anyone else "understands" where a random block of code belongs, or the context that the code is supposed to be executed within.

This sample calls for the context of an activity, which houses the getAssets() method. Within the android platform, their are other classes besides Activity which can supply this context. One example is the (generic reference) Service class.

Saying answered 6/11, 2017 at 15:41 Comment(2)
"complete" means within the method/class headers; and WITH NO generic ellipsized code generalizations such as: ... do some thing .... A beginner would not know the difference between pseudo code and actual code.Saying
you need to fix + ((assetsFolder.endsWith(File.pathSeparator))?"":File.pathSeparator) + the result is : instead of / or \ i change it to + "/" + and the code work perfectly please update the code it takes me about 1h SearchingHemialgia
E
1

Moving an arbitrary folder of directories and files from Assets

The thing is... Assets are special. You cannot wrap it in a File object and ask isDirectory() and you cannot pass these assets into the NDK. So it is better to wrap them up and move them to a cache directory or onto the SDCard which is why you're here.

I've seen many SO answers that involve some version of rolling through an array of fileOrDirectoryName strings and then creating directories followed by a recursive call and copying individual files. Which leads you to create a folder or file and you cannot tell from an asset which you have.

Make it a Zip file

My recommendation is to take each arbitrary collection of assets that you want to ship to the SDCard or an internal cache folder and Zip it up. The problem is structured in an way more compatible with the Assets concept.

AssetManager assetManager = context.getAssets();
String fullAssetPath = fromAssetPath + "/" + zipFilename;
String toPath = "/wherever/I/want";

try {
    InputStream inputStream = assetManager.open(fullAssetPath);
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));

    ZipEntry zipEntry;
    byte[] buffer = new byte[8192];
    while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        String fileOrDirectory = zipEntry.getName();

        Uri.Builder builder = new Uri.Builder();
        builder.scheme("file");
        builder.appendPath(toPath);
        builder.appendPath(fileOrDirectory);
        String fullToPath = builder.build().getPath();

        if (zipEntry.isDirectory()) {
            File directory = new File(fullToPath);
            directory.mkdirs();
            continue;
        }   

        FileOutputStream fileOutputStream = new FileOutputStream(fullToPath);
        while ((count = zipInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, count);
        }
        fileOutputStream.close();
        zipInputStream.closeEntry();
    }

    zipInputStream.close();

} catch (IOException e) {
    Log.e(TAG, e.getLocalizedMessage());
}

Small note about buffer sizes

I've seen a lot of examples involving very small buffer sizes, for example 1024. Unless you just want to waste time feel free to try larger byte buffer sizes. Even my choice of 8192 is probably small on modern hardware.

Avoiding Stringy paths

Notice the use of Uri.Builder to construct the path. I much prefer this style of path construction over directory + "/" + file. Then you're in the business, for the sake of consistency avoiding assigning String d = "myDirectory/" or String f = "/file.txt" and other such string hacking nonsense.

Egwan answered 23/2, 2017 at 12:27 Comment(2)
Thanks, i was looking for a model to perform such a function.Saying
@Cameron Lowell Palmer any downside to putting your example inside an AsyncTask or ExecutorService using Executors.newSingleThreadExecutor()?Damicke
S
1

Here's a recursive solution written in kotlin. It works with both files and dirs.

Usage - copyAssetDir(context, "<asset path>", "<dest dir>")

import android.content.Context
import java.io.File
import java.io.FileOutputStream

fun copyAssetDir(context: Context, assetPath: String, destDirPath: String) {
    walkAssetDir(context, assetPath) {
        copyAssetFile(context, it, "$destDirPath/$it")
    }
}

fun walkAssetDir(context: Context, assetPath: String, callback: ((String) -> Unit)) {
    val children = context.assets.list(assetPath) ?: return
    if (children.isEmpty()) {
        callback(assetPath)
    } else {
        for (child in children) {
            walkAssetDir(context, "$assetPath/$child", callback)
        }
    }
}

fun copyAssetFile(context: Context, assetPath: String, destPath: String): File {
    val destFile = File(destPath)
    File(destFile.parent).mkdirs()
    destFile.createNewFile()

    context.assets.open(assetPath).use { src ->
        FileOutputStream(destFile).use { dest ->
            src.copyTo(dest)
        }
    }

    return destFile
}
Smoothen answered 8/4, 2020 at 11:43 Comment(0)
D
0

This is code for copy assets folder with directory and files both copy into sdcard folder... this one works perfectly for me...

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

}
Delirious answered 2/1, 2018 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.