android – Copying raw file into SDCard?-ThrowExceptions

Exception or error:

I’ve some audio files in my res/raw folder. For some reasons, i want to copy this files to my SDCard When, my application starts.

How can i done this? Anyone guide me?

How to solve:

Read from the resource, write to a file on the SD card:

InputStream in = getResources().openRawResource(R.raw.myresource);
FileOutputStream out = new FileOutputStream(somePathOnSdCard);
byte[] buff = new byte[1024];
int read = 0;

try {
   while ((read = in.read(buff)) > 0) {
      out.write(buff, 0, read);
   }
} finally {
     in.close();
     out.close();
}

###

Copy file from raw to External Storage:

This is a method that i use to do this job, this method receive the resource id, and the name desired for storage, for example:

copyFiletoExternalStorage(R.raw.mysound, "jorgesys_sound.mp3");

method:

private void copyFiletoExternalStorage(int resourceId, String resourceName){
    String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
    try{
        InputStream in = getResources().openRawResource(resourceId);
        FileOutputStream out = null;
        out = new FileOutputStream(pathSDCard);
        byte[] buff = new byte[1024];
        int read = 0;
        try {
            while ((read = in.read(buff)) > 0) {
                out.write(buff, 0, read);
            }
        } finally {
            in.close();
            out.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

###

Environment.getExternalStorageDirectory() this method is
deprecated in API level 29 and it will not allow to create a
directory/file on given path.

Below code is working for creating directory and downloading file from /res/raw directory.

If your device have Android 10 (API Level 29) or greater it will
download your file on below location

File manager–> Storage –>
Android –> data –> com.yourapp.packagename –> files –> FOLDER_NAME
–> file_name.png

private void downloadFileFromRawFolder(){
try {
                InputStream in = getResources().openRawResource(
                        getResources().getIdentifier("file_name",
                                "raw", getPackageName())); // use only file name here, don't use extension
                File fileWithinMyDir = new File(checkFolder(), "file_name.png"); //Getting a file within the dir.
                Log.e("FILEPATH ", "fileWithinMyDir " + fileWithinMyDir);
                FileOutputStream out = new FileOutputStream(fileWithinMyDir);
                byte[] buff = new byte[1024 * 1024 * 2]; //2MB file
                int read = 0;

                try {
                    while ((read = in.read(buff)) > 0) {
                        out.write(buff, 0, read);
                    }
                } finally {
                    in.close();
                    out.close();
                }
                Log.d(TAG, "Download Done ");
            } catch (IOException e) {
                Log.e(TAG, "Download Failed " + e.getMessage());
                e.printStackTrace();
            }

}

/* Create directory */

    private File checkFolder() {
        String path;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            path = getExternalFilesDir(null).getAbsolutePath() + "FOLDER_NAME";
        } else {
            path = Environment.getExternalStorageDirectory() + "FOLDER_NAME";
        }
        File dir = new File(path);
        boolean isDirectoryCreated = dir.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = dir.mkdir();
            Log.d("Folder", "Created = " + isDirectoryCreated);
        }

        Log.d("Folder", "Created ? " + isDirectoryCreated);
        return dir;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *