Recidentally copy resources from Assets to Internal Memory in Android?

0

I have several resources in the src/assets/ folder I need to copy as they are in another location, accessible to the user, internal memory documents or sdcard .

Taking into account recursion, if within the source there is a directory also copy the resources of the directory.

It would be interesting, if in the destination they are already found, that with a parameter you can decide whether to overwrite or not.

    
asked by Webserveis 14.08.2016 в 19:21
source

1 answer

0

Adapting a response from SO from @DannyA

private void copyAssets(String path, String outPath) {
    AssetManager assetManager = this.getAssets();
    String assets[];
    try {
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(path, outPath);
        } else {
            String fullPath = outPath + "/" + path;
            File dir = new File(fullPath);
            if (!dir.exists())
                if (!dir.mkdir()) Log.e(TAG, "No create external directory: " + dir );
            for (String asset : assets) {
                copyAssets(path + "/" + asset, outPath);
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "I/O Exception", ex);
    }
}

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

    InputStream in;
    OutputStream out;
    try {
        in = assetManager.open(filename);
        String newFileName = outPath + "/" + 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();
        out.flush();
        out.close();
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

}

Prerequisites

In the directory src/main/assets we will create a folder fold and there is where to put the files.

Your Use

File outDir =  new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
copyAssets("fold",outDir.toString());
    
answered by 15.08.2016 / 12:54
source