How to download the files in specific folder in internal storage

android save file to internal storage example
android download file from url and save to internal storage
path internal storage download
create folder in internal storage android programmatically
how to get internal and external storage path android
android list files in internal storage
android write text file internal storage
android read file from internal storage

I am trying to create a separate folder in internal storage of a phone for an app to download files on it. But the folder is not created in the phone. What is the reason? Also I have another issue in my app that is photos are not downloaded when I click thee download button.

Here is the download function

    public void download() {
    for (MediaModel item : Items) {

       if (item.isSelected) {

            Log.d("check", "download");
            final String url = item.getFullDownloadURL();
            BaseDownloadTask task = FileDownloader.getImpl().create(url);
            task.setListener(mFileDownloadListener)
            .setPath(Environment.getDataDirectory() + "/" + Constants.STORED_FOLDER, true)
                    .setAutoRetryTimes(1)
                    .setCallbackProgressTimes(0)
                    .asInQueueTask()
                    .enqueue();

            if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
                item.setTaskId(task.getId());
                item.setStatus(ItemStatus.DOWNLOADING);
                Logging.e(TAG, "start download task: " + task.getId());
            } else {
                item.setTaskId(task.getId());
                item.setStatus(ItemStatus.NORMAL);
                Logging.e(TAG, "error download task: " + task.getId());
            }
        }
    }
}

In Android studio to use internal Storage First of all add permission in manifest Like this:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

then to make new directory in internal storage use this line of code:

   File sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");

        if (!sdCardRoot.exists()) {
            sdCardRoot.mkdirs();
        }

        Log.e("check_path", "" + sdCardRoot.getAbsolutePath());

This is my full code:

In this code check directory is exist or not if directory is not exist then create directory and use asyntask to download images from url

In this example i have use Java Language

Code

  MyAsyncTasks asyncTasks = new MyAsyncTasks();
                asyncTasks.execute(Imageurl);

and AsyncClass:

class MyAsyncTasks extends AsyncTask<String, String, String> {

File sdCardRoot;

@Override
protected String doInBackground(String... strings) {

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strings[0]);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();


        sdCardRoot = new File(Environment.getExternalStorageDirectory(), "MyProfile");

        if (!sdCardRoot.exists()) {
            sdCardRoot.mkdirs();
        }

        Log.e("check_path", "" + sdCardRoot.getAbsolutePath());

        String fileName =
                strings[0].substring(strings[0].lastIndexOf('/') + 1, strings[0].length());
        Log.e("dfsdsjhgdjh", "" + fileName);
        File imgFile =
                new File(sdCardRoot, fileName);
        if (!sdCardRoot.exists()) {
            imgFile.createNewFile();
        }
        InputStream inputStream = urlConnection.getInputStream();
        int totalSize = urlConnection.getContentLength();
        FileOutputStream outPut = new FileOutputStream(imgFile);
        int downloadedSize = 0;
        byte[] buffer = new byte[2024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            outPut.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            Log.e("Progress:", "downloadedSize:" + Math.abs(downloadedSize * 100 / totalSize));
        }
        Log.e("Progress:", "imgFile.getAbsolutePath():" + imgFile.getAbsolutePath());

        Log.e(TAG, "check image path 2" + imgFile.getAbsolutePath());

        mImageArray.add(imgFile.getAbsolutePath());
        outPut.close();
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("checkException:-", "" + e);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    imagecount++;
    Log.e("check_count", "" + totalimagecount + "==" + imagecount);
    if (totalimagecount == imagecount) {
        pDialog.dismiss();
        imagecount = 0;
    }
    Log.e("ffgnjkhjdh", "checkvalue checkvalue" + checkvalue);


   }


  }

Access app-specific files, Before writing app-specific files to internal storage, your app should query the a file as a stream at install time, save the file in your project's /res/raw directory. Downloading directly to cloud means to download files to online cloud drive storage via web link or URL which indicates where the source files locates. The web link is usually generated while the owner of the file share it to others, maybe his families, friends, colleagues and so on.

Try This code:

 private class DownloadingTask extends AsyncTask<Void, Void, Void> {

    File apkStorage = null;
    File outputFile = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog=new ProgressDialog(context);
        progressDialog.setMessage("Downloading...");
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        try {
            if (outputFile != null) {
                progressDialog.dismiss();
                CDToast.makeText(context, context.getResources().getString(R.string.downloaded_successfully), CDToast.LENGTH_SHORT, CDToast.TYPE_SUCCESS).show();
                Notification();
                vibrateDevice(100);
            } else {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                    }
                }, 3000);

                CDToast.makeText(context, context.getResources().getString(R.string.download_failed), CDToast.LENGTH_SHORT, CDToast.TYPE_ERROR).show();


            }
        } catch (Exception e) {
            e.printStackTrace();

            //Change button text if an exception occurs

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                }
            }, 3000);
            Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());

        }


        super.onPostExecute(result);
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            URL url = new URL(downloadUrl);//Create Download URl
            HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
            c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
            c.connect();//connect the URL Connection

            //If Connection response is not OK then show Logs
            if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                        + " " + c.getResponseMessage());

            }


            //Get File if SD card is present
            if (new CheckForSDCard().isSDCardPresent()) {

                apkStorage = new File(
                        Environment.getExternalStorageDirectory() + "/"
                                + "New_Folder_Name_Here");
            } else
                Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();

            //If File is not present create directory
            if (!apkStorage.exists()) {
                apkStorage.mkdir();
                Log.e(TAG, "Directory Created.");
            }

            outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

            //Create New File if not present
            if (!outputFile.exists()) {
                outputFile.createNewFile();
                Log.e(TAG, "File Created");
            }

            FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location

            InputStream is = c.getInputStream();//Get InputStream for connection

            byte[] buffer = new byte[1024];//Set buffer type
            int len1 = 0;//init length
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);//Write new file
            }

            //Close all connection after doing task
            fos.close();
            is.close();

        } catch (Exception e) {

            //Read exception if something went wrong
            e.printStackTrace();
            outputFile = null;
            Log.e(TAG, "Download Error Exception " + e.getMessage());
        }

        return null;
    }
}

For Checking SD card :

public class CheckForSDCard {


//Check If SD Card is present or not method
public boolean isSDCardPresent() {
    if (Environment.getExternalStorageState().equals(

            Environment.MEDIA_MOUNTED)) {
        return true;
    }
    return false;
     }
  }

Data and file storage overview, App-specific files, Files meant for your app's use only, From internal storage, Other types of shareable content, including downloaded files, Storage Access app is starting up, place the data within internal storage directory or a database. To create a file to internal storage, first you need to get directory. There are two types of directories, temporary cache directory and directory for permanent files. Files stored in temporary directory are removed by the system to free up storage space. To get internal directory for your app, call getFilesDir().

For creating folder

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your Folder Name";
    File folder = new File(path);
    if (!folder.exists()) {
        folder.mkdir();
    }

also refer to this answer: https://stackoverflow.com/a/35471045/9060917

Update

public void download() {
    for (MediaModel item : Items) {
        if (item.isSelected) {
            File file = new File(getFilesDir(),"Your directory name");
if(!file.exists()){
    file.mkdir();
}

try{
    Log.d("check", "download");
            final String url = item.getFullDownloadURL();
            BaseDownloadTask task = FileDownloader.getImpl().create(url);
            task.setListener(mFileDownloadListener)
                .setPath(file.getAbsolutePath(), true)
                .setAutoRetryTimes(1)
                .setCallbackProgressTimes(0)
                .asInQueueTask()
                .enqueue();

}catch (Exception e){
    e.printStackTrace();

}

        if (FileDownloader.getImpl().start(mFileDownloadListener, true)) {
            item.setTaskId(task.getId());
            item.setStatus(ItemStatus.DOWNLOADING);
            Logging.e(TAG, "start download task: " + task.getId());
        } else {
            item.setTaskId(task.getId());
            item.setStatus(ItemStatus.NORMAL);
            Logging.e(TAG, "error download task: " + task.getId());
            }
        }
    }
}

I hope you add these permissions in manifests

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Update

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling method

getFilesDir()

 File directory = context.getFilesDir();
 File file = new File(directory, filename);

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:

 String filename = "myfile";
 String fileContents = "Hello world!";
 FileOutputStream outputStream;

 try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
 } catch (Exception e) {
e.printStackTrace();
}

More reference

https://developer.android.com/training/data-storage/files#java

Managing files, Smart folders show all images, videos, music, or downloaded files stored anywhere on Removable storage devices can be an SD card in your phone or a USB� How to download Chrome Browser APK file internal storage and SD card ki Chrome Browser se koi bhi apk file SD card mein kaise download Karen Agar video Pasand Aaye To like share and comment

pass the URL of the image you want to download in this method.

  /*--Download Image in Storage--*/
public void downloadImage(String URL) {
    final Long reference;
    downloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(URL);
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setTitle("AppName");
    request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
            getString(R.string.app_name)), "FileName.jpg");
    Log.i("myi", "downloadImage: " + request.setDestinationInExternalPublicDir(String.format("%s/%s", Environment.getExternalStorageDirectory(),
            getString(R.string.app_name)), "FileName.jpg"));

    request.setVisibleInDownloadsUi(true);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    reference = downloadManager.enqueue(request);

    Log.d("download", "Image Download : " + reference);

    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                Toast.makeText(this, "Image Downloaded Successfully ", Toast.LENGTH_LONG);
            } catch (Exception e) {
            }
        }
    };
    getApplicationContext().registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

Can I download folders from Google Drive to my Android device , There you can then copy even folders to your internal storage. Open Files. Press on the button to open the side menu. Select Drive. Go to the folder you wish to� App-specific storage: Store files that are meant for your app's use only, either in dedicated directories within an internal storage volume or different dedicated directories within external storage. Use the directories within internal storage to save sensitive information that other apps shouldn't access.

Handling Files in Code After Android 10 Released, Scoped Storage gives the ability to create a second folder for files the app the app-specific cache directory on the internal storage of your device, files and other files, Shared storage directories include the Download,� Other apps cannot access files stored within internal storage. This makes internal storage a good place for app data that other apps shouldn't access. Keep in mind, however, that these directories tend to be small. Before writing app-specific files to internal storage, your app should query the free space on the device. Access persistent files

Find & delete files on Android - Android Help, On your phone, you can usually find your files in the Files app Files app . Learn how to get help for your specific device. When you connect your phone to a computer by USB cable, open the computer's "Downloads" folder to find the files � The stored data in memory is allowed to read and write files. When files are stored in internal storage these file can only be accessed by the application itself not by other applications. These files in storage exist till the application stays over the device, as you uninstall associated files get removed automatically.

Android Phones For Dummies, On most Android phones, specific folders are used for file organization. Here are This folder contains files you've downloaded using the phone'sweb browser app. These folders can exist on either the internal storage or the microSD card. Hello everyone, creating new file is most needed on develop android app. Here i showing to you how to creating new folder in using android studio and save files to custom folders. SOURCE CODE

Comments
  • Possible duplicate please refer at stackoverflow.com/questions/12971684/…
  • @ralphgabb But that will create a folder in external storage root. I want to create folder in internal storage.
  • Can you please tell me what is the purpose of mImageArray.add(imgFile.getAbsolutePath()). What is mImageArray here?
  • mImageArray.add(imgFile.getAbsolutePath()). its used to add save image path in arraylist if you have not save imagepath in list then forgot it.
  • in this code i have try to save download image path in arraylist for future use.
  • The issue is the folder is not created in some android phones. It is not visible in the internal storage. Can you explain the reason?
  • please tell me in which device or os folder not created
  • This is not working in my download function. Can you explain this in my code
  • I tried this code. But I got the error "can not resolve method exists(), can not resolve mkdir(). There exist another error in File folder = new File(path);
  • make sure you import " import java.io.File;"
  • yes. I did. But the same problem. I have another query getExternalStorageDirectory() is used for external storage can I use it to create folder in internal storage?
  • I tried this. But it is not working in my download() function. Can you please explain this in my code.