Copying raw file into SDCard?

后端 未结 3 2017
灰色年华
灰色年华 2020-11-28 14:43

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?

3条回答
  •  伪装坚强ぢ
    2020-11-28 15:42

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

提交回复
热议问题