Android - Copy files from assets to /data/data folder

superuser picture superuser · Apr 7, 2014 · Viewed 29.2k times · Source

I need to use some files in my app. They are kept in asset folder. I saw discussions on SO, where the files are being copied from asset folder, to /data/data/<package_name> on the internal storage, and then being used. I get the code, but what I do not get is, what is the need to copy the assets to internal storage?

Answer

Lavekush Agrawal picture Lavekush Agrawal · Apr 7, 2014

Try this:(Use all three method its work for me and assign destination path in "toPath" string object)

  String toPath = "/data/data/" + getPackageName();  // Your application path


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