How to download file into Any Storage (SD,OTG,Phone) in Android Devices

July 31, 2020

Download File into Any Storage (SD,OTG,Phone) in android device, we have to follow these steps:

Step 1:

we have to give permission to write or download a file into Storage (SD,OTG,Phone).

  1. Give permission into AndroidManifest.xml.
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Give permission of storage into manifest file

  1. Give permission to write file into SD card using Document File

we have to call intent to open DocumentFile to access SD card which shows like this:

      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
      startActivityForResult(intent, 42);

Open Actin sheet of DocumentFile to choose SD Card

  1. When we select SD Card from action sheet, then @override method onActivityResult method call automatically. i.e;
      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          if (resultCode != RESULT_OK)
          else {
              Uri treeUri = data.getData();
              pickedDir = DocumentFile.fromTreeUri(this, treeUri);
              final int takeFlags = data.getFlags()
                      & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                      | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
              getApplicationContext().getContentResolver().takePersistableUriPermission(treeUri, takeFlags);


@override onActivityResult

  1. Variable pickedDir is the path where user want to create file or Directory.
      pickedDir.createDirectory("New Folder");
      pickedDir.createFile("Image/png", filename);

“Image/png” is mime type of file.

  1. How to Download File and save into SD card using DocumentFile
    URL url = new URL(";
    Uri u = Uri.parse(";
    File f = new File("" + u);
    String filename = f.getName();
    URLConnection conection =url.openConnection();
    ((URLConnection) conection).connect();
    int lenghtOfFile = conection.getContentLength();
    InputStream input = new BufferedInputStream(
            url.openStream(), 8192);
    DocumentFile ff = pickedDir.createFile("Image/png", filename);
    OutputStream output = getApplicationContext().getContentResolver().openOutputStream(ff.getUri(),"w");
    byte data[] = new byte[1024];
    long total = 0;
    while ((count = != -1) {
        total += count;
        publishProgress((int) ((total * 100)/lenghtOfFile));
        output.write(data, 0, count);

Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow