Che
Che

Reputation: 49

How to save a file to external storage in the media directory in 2020?

I have a question.

How can I save a file from network to the external storage of the android device, with Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) being depricated?

My Code:

    private void download(Context mContext) throws IOException {
        String requestUrl = "http://someresource/..."
        URL url = new URL(requestUrl);
        InputStream in = url.openStream();
        mContext.getFilesDir();
        URI uri = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_MUSIC).toURI();
        Files.copy(in, Paths.get(uri.getPath() + "/_test.mp3"), StandardCopyOption.REPLACE_EXISTING);
        in.close();
        System.out.println("finished!");
    }

I get the error W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Music/_test.mp3

I also read the article https://developer.android.com/training/data-storage/shared/media#java but I suppose this is meant to be more of a guideline to tamper with existing media files, like searching or editing file tags etc. and not simply saving a file in the media directory.

Update: My app needs to fulfill two tasks. I want to save an mp3 file to the above mentioned directory and also read files from this directory.

Below Q: Working with Environment.getExternalStorageDirectory().getPath()+"/Music"; returns the Music-Folder on the built-in flash memory of the Android device. In that manner I want to know how to get the Music-Folder on the SD-Card of the Android device (when its plugged in).

Since Q: the above Method returns a directory, which is no longer directly accessible to apps. The tasks I want to fulfil are the same as the ones mentioned above. As @blackapps supposed, using the MediaStore Class is in Q preferable. But how exactly do I do that?

Upvotes: 3

Views: 1261

Answers (1)

Bellal Hossain
Bellal Hossain

Reputation: 250

For android 10 and 11 add this line to your <application> element in the android manifest file. hope it will work:

<application
android:requestLegacyExternalStorage="true"

Upvotes: 2

Related Questions