copy directory from assets to data folder
Asked Answered
H

2

10

I would like to copy a quite big directory from the assets folder of my app to the data folder on the first run of the app. How do I do that? I already tried some examples, but nothing worked, so I don't have anything. My target is Android 4.2.

Thanks, Yannik

Hireling answered 7/6, 2013 at 12:19 Comment(2)
Why would you do that? If I am not mistaking data and asset folder will live for as long as the app is installed.Celadon
Check this It may useful for you guys #4447977Ramose
C
24

try this code of your Application instance (you should write the class in manifest): This code is copying content of assets/files folder to the cache folder of app (you can place other path in copyAssetFolder() function). Only when App is launched for the first time

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.preference.PreferenceManager;

public class MyApplication extends Application {
    private static Context  s_sharedContext;

    @Override
    public void onCreate () {
        super.onCreate();   
        if (!PreferenceManager.getDefaultSharedPreferences(
                getApplicationContext())
            .getBoolean("installed", false)) {
            PreferenceManager.getDefaultSharedPreferences(
                    getApplicationContext())
                .edit().putBoolean("installed", true).commit();

            copyAssetFolder(getAssets(), "files", 
                    "/data/data/com.example.appname/files");
        }
    }

    private static boolean copyAssetFolder(AssetManager assetManager,
            String fromAssetPath, String toPath) {
        try {
            String[] files = assetManager.list(fromAssetPath);
            new File(toPath).mkdirs();
            boolean res = true;
            for (String file : files)
                if (file.contains("."))
                    res &= copyAsset(assetManager, 
                            fromAssetPath + "/" + file,
                            toPath + "/" + file);
                else 
                    res &= copyAssetFolder(assetManager, 
                            fromAssetPath + "/" + file,
                            toPath + "/" + file);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean copyAsset(AssetManager assetManager,
            String fromAssetPath, String toPath) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(fromAssetPath);
          new File(toPath).createNewFile();
          out = new FileOutputStream(toPath);
          copyFile(in, out);
          in.close();
          in = null;
          out.flush();
          out.close();
          out = null;
          return true;
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

}
Christophe answered 7/6, 2013 at 12:25 Comment(5)
Thanks, but I wanted to put it the the data folder because I would like to run a script which inside the folder.Hireling
What folder do you mean? Can you write absolute path of this?Christophe
for example /data/data/com.example.appname/Hireling
as far as I know you can not do it, but you can use folder /data/data/com.example.appname/files - see updated codeChristophe
let us continue this discussion in chatChristophe
A
1
private fun copyAssets(
    assetManager: AssetManager,
    assetPath: String,
    outputPath: String
) {
    // check if asset path is a file. if file exists, then it is copied to the output path
    try {
        // throws IOException when file does not exist
        val assetFd = assetManager.openFd(assetPath)
        // file exists, so file is copied to the output path
        copyFile(assetFd, outputPath)
    } catch (e: Exception) {
        try {
            // file does not exist
            // try to list asset path content
            val files = assetManager.list(assetPath)
            // create output directory if not exist
            val outputDir = File(outputPath)
            outputDir.mkdirs()
            // loop through asset path directory and copy content recursively
            files?.forEach { file ->
                // new asset path is set to file
                val newAssetPath = "$assetPath/$file"
                // set relative output file path
                val newOutputPath = "$outputPath/$file"
                // recursively copy from asset path to the output path
                copyAssets(assetManager, newAssetPath, newOutputPath)
            }
        } catch (e: java.lang.Exception) {
            // asset path is neither a file nor a directory
            throw IOException("asset path does not exist")
        }
    }
}

/**
 * copy file from asset file descriptor to the output file path
 */
private fun copyFile(inputFd: AssetFileDescriptor, outputFilePath: String) {
    val inputStream = inputFd.createInputStream()
    val outputStream = FileOutputStream(outputFilePath)
    val buffer = ByteArray(8192)
    var read = inputStream.read(buffer)
    while (read != -1) {
        outputStream.write(buffer, 0, read)
        read = inputStream.read(buffer)
    }
    inputStream.close()
    outputStream.close()
}

A directory can be copied from assets to data directory in the following way

val assetPath = "resources"
val outputPath = "${appContext.filesDir.absolutePath}/resources"
val assetManager = appContext.resources.assets
copyAssets(assetManager, assetPath, outputPath)
Abbate answered 17/7, 2021 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.