Copy directory from Assets to local directory

android copy file from assets to internal storage
copy file from sdcard to assets folder in android
copy file from assets to external storage android
how to get absolute path of assets folder in android
xamarin android copy file from assets to internal storage
kotlin copy file from assets
android extract assets
how to get filename from assets folder in android

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

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!

Function to recursively copy files from an Android asset directory , Function to recursively copy files from an Android asset directory. gistfile1.txt. public void copyFileOrDir(String path) {. AssetManager assetManager = this. How to Copy a Directory in Linux Command Line [Beginner's Tip] This quick tip for beginners demonstrates how to copy a directory in Linux using the cp command. You'll also learn a few additional tips around copying directory.


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.size == 0) {
            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 `in` = this.open(srcName)
        val outFile = File(dstName)
        val out: OutputStream = FileOutputStream(outFile)
        val buffer = ByteArray(1024)
        var read: Int
        while (`in`.read(buffer).also { read = it } != -1) {
            out.write(buffer, 0, read)
        }
        `in`.close()
        out.close()
        true
    } catch (e: IOException) {
        e.printStackTrace()
        false
    }
}

Copy directory from Assets to local directory, 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? How to: Copy directories. 12/27/2018; 2 minutes to read +8; In this article. This topic demonstrates how to use I/O classes to synchronously copy the contents of a directory to another location. For an example of asynchronous file copy, see Asynchronous file I/O. This example copies subdirectories by setting the copySubDirs of the DirectoryCopy


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

Using the Static Folder, Adding assets outside of the module system. You can create a folder named static at the root of your project. Every file you put into that folder will be copied into� Omitting the slash on the source directory will copy the contents into a subdirectory. To omit files from being copied check out our guide on how to exclude files and directories in data transfer using rsync command .


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.

Assets, You can also use Static directory for static assets. Assets. By default, Nuxt uses vue-loader, file-loader and url-loader webpack loaders for strong assets serving. file-loader lets you designate where to copy and place the asset file, and how� You can copy the files from different directories into a new location. cp docs/* scripts/* tmp/ The command copies the files from docs and script directories to the destination directory tmp. 8. Write a unix/linux cp command to Copy a directory. You can recursively copy a complete directory and its sub directory to another location using the cp


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.

Copying projects, folders, and assets - Informatica, When you copy assets or a folder containing assets to another location, the assets retain their references to dependent objects. For example, a folder in the� Copy command can be used to copy files from one folder to another folder. It can’t be used to copy a complete folder to another location on the disk. Xcopy allows us to do this. Let’s see how we can copy a directory along with all the files and sub directories to another location. Xcopy /E /I SourceFolder DestinationFolder


Local Assets, Lets dive in and look at an example of how to use local assets: assets folder, this instructs the Stencil compiler to copy that folder into the distribution folder� You can also use Guava's ByteStream to copy the files from the assets folder to the SD card. This is the solution I ended up with which copies files recursively from the assets folder to the SD card: /** * Copies all assets in an assets directory to the SD file system.


Access app-specific files, Copy and paste � Drag and drop � Picture-in-picture Support Play Asset Delivery In many cases, your app creates files that other apps don't need to access, Internal storage directories: These directories include both a dedicated might be larger than the current amount of free space on the device. Copy the contents of a directory into another directory. Move to the directory where you want to copy the directories and subdirectories. In the example below, we are moving to the temp2 directory using the cd command. cd\temp2. Once in the directory, use the xcopy command to copy another directory's subdirectories and contents.


Adobe LiveCycle ES4 * Working with assets, However, when you copy such an asset into another application, it becomes a LiveCycle When you first create an asset, it is created in your local folder.