Search code examples
androidfilecopyassets

copying the entire folder with its contents from assets to internal app files/


Please, suggest me the best way of copying a folder from assets to /data/data/my_app_pkg/files.

The folder from assets (www) contains files and subfolders. which I want to completely copy to the files/ of my internal app path mentioned.

I am successfully able to copy a file from assets to internal app files/ path, but unable to do the same in case of copying folder, even assetmanager.list isn't helping me out, as it is copying only the files, but not the directories / subfolders.

Please kindly suggest me the better way to do what I want


Solution

  • Hope use full to you below code:-

    Copy files from a folder of SD card into another folder of SD card

    Assets

                AssetManager am = con.getAssets("folder/file_name.xml");
    
    
     public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
        throws IOException {
    
    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();
        }
    
        String[] children = sourceLocation.list();
        for (int i = 0; i < sourceLocation.listFiles().length; i++) {
    
            copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {
    
        InputStream in = new FileInputStream(sourceLocation);
    
        OutputStream out = new FileOutputStream(targetLocation);
    
        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
    
    }