Android: How to create a directory on the SD Card and copy files from /res/raw to it?

This will copy all files in the “clipart” subfolder of the .apk assets folder to the “clipart” subfolder of your app’s folder on the SD card:

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    String basepath = extStorageDirectory + "/name of your app folder on the SD card";
//...

// in onCreate
File clipartdir = new File(basepath + "/clipart/");
        if (!clipartdir.exists()) {
            clipartdir.mkdirs();
            copyClipart();      
        }

private void copyClipart() {
        AssetManager assetManager = getResources().getAssets();
        String[] files = null;
        try {
            files = assetManager.list("clipart");
        } catch (Exception e) {
            Log.e("read clipart ERROR", e.toString());
            e.printStackTrace();
        }
        for(int i=0; i<files.length; i++) {
            InputStream in = null;
            OutputStream out = null;
            try {
              in = assetManager.open("clipart/" + files[i]);
              out = new FileOutputStream(basepath + "/clipart/" + files[i]);
              copyFile(in, out);
              in.close();
              in = null;
              out.flush();
              out.close();
              out = null;
            } catch(Exception e) {
                Log.e("copy clipart ERROR", e.toString());
                e.printStackTrace();
            }       
        }
    }
    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);
        }
    }

Leave a Comment