how to download file and save in SD card on android?

         try {
            URL url = new URL(file_url);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download";
            File file = new File(PATH);
            if(!file.exists()) {
                file.mkdirs(); 
            }
            String name=String.valueOf(code)+".mp4";
            File outputFile = new File(file,name);
            FileOutputStream fos = 
                     new FileOutputStream(outputFile);//this line

            InputStream is = c.getInputStream();
            int fileLength = sizeoffile;

            byte[] buffer = new byte[4096];
            int len1 = 0;
            long total = 0;
            while ((len1 = is.read(buffer)) != -1) {
                total += len1;
                if (fileLength > 0) 
                    publishProgress((int) (total));
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

i want to download file with async class but it error when i rather to find the file path? this is a error in up to android 6? java.io.FileNotFoundException: /sdcard/downloadedfile.jpg: open failed: ENOENT (No such file or directory)

i added these permissions but doesn't work!

2 answers

  • answered 2017-08-12 09:29 Faizal Abbas

    You first have to check if the directory exists or not if it doesn't exists then you have to make directory first

    File dir = new File("path/to/your/directory");
    try{
      if(dir.mkdir()) {
         System.out.println("Directory created");
      } else {
         System.out.println("Directory is not created");
      }
    }catch(Exception e){
      e.printStackTrace();
    }
    

  • answered 2017-08-12 10:00 Gowthaman M

    Try this following code download files:

      class Download_file extends AsyncTask<String,Integer,String>
            {
                int length;
                String filenames="";
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    mProgressDialog = new ProgressDialog(context);
                    mProgressDialog.setMessage("Here you can set a message");
                    mProgressDialog.setIndeterminate(false);
                    mProgressDialog.setMax(100);
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    mProgressDialog.show();
    
    
                }
    
                @Override
                protected String doInBackground(String... strings) {
                    int count;
    
                    try {
                        URL url = new URL(strings[0]);
                        filenames = strings[0];
                        URLConnection connection = url.openConnection();
                        connection.connect();
    
                        // this will be useful so that you can show a tipical 0-100% progress bar
                  File dir= new File(Environment.getExternalStorageDirectory() + 
                          "/Download/Reports/");
                        dir.mkdirs();
    
                       String PATH = Environment.getExternalStorageDirectory() + 
                                 "/Download/Reports/";
                        if (!(new File(PATH)).exists()) {
                            new File(PATH).mkdirs();
                        }
    
                         length = connection.getContentLength();
                        filesize = length;
                        File file = new File(dir,""+ sample+".pdf");
    
                        Log.d("filepath","*****   "+file);
    
                        // downlod the file
                        InputStream input = new BufferedInputStream(url.openStream());
    
                        OutputStream output = new FileOutputStream(file);
                        byte data[] = new byte[1024];
    
                        long total = 0;
    
                        while ((count = input.read(data)) != -1) {
                            total += count;
                            // publishing the progress....
                            publishProgress((int)(total*100/length));
                            output.write(data, 0, count);
                        }
                        output.flush();
                        output.close();
                        input.close();
    
                         /* File file = new File(myNewFolder, "Week" + pptx_filestore_postion + ".pptx");
    
    
                    // Output stream
                    OutputStream output = new FileOutputStream(file);*/
    
    
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
    
                        Log.d("MalformedURLException","Filedonwload"+e.toString());
    
                    } catch (IOException e) {
    
                        e.printStackTrace();
                        Log.d("IOException","Filedonwload"+e.toString());
                    }
    
    
                    return null;
    
                }
    
                @Override
                protected void onProgressUpdate(Integer... values) {
                   // mProgressDialog.setProgress(values[0]);
                  //  mProgressDialog.setProgressNumberFormat((values[1]/(1024*1024)) + "" +(values[1]/(1024*1024)));
                    mProgressDialog.setProgress(values[0]);
                    mProgressDialog.setProgressNumberFormat((bytes2String(values[0])) + "/" + (bytes2String(filesize)));
                }
    
                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
    
                  //  mProgressDialog.dismiss();
    
    
                    /*Environment.getExternalStorageDirectory() + "/Download/Idea_Reports/*/
                    String filepath_fromsdcared = Environment.getExternalStorageDirectory().toString() + dir +filenames+"csv";
    
    
                    // setting downloaded into image view
                    //dismissDialog(progress_bar_type);
                    Log.d("filepath", "====" + filepath_fromsdcared);
                }
            }
    

    Use this function for file size downloading progress update

    Declare variables:
    
        private static double SPACE_KB = 1024;
        private static double SPACE_MB = 1024 * SPACE_KB;
        private static double SPACE_GB = 1024 * SPACE_MB;
        private static double SPACE_TB = 1024 * SPACE_GB;
    
    
      public static String bytes2String(long sizeInBytes) {
    
            NumberFormat nf = new DecimalFormat();
            nf.setMaximumFractionDigits(2);
    
            try {
                if ( sizeInBytes < SPACE_KB ) {
                    return nf.format(sizeInBytes) + " Byte(s)";
                } else if ( sizeInBytes < SPACE_MB ) {
                    return nf.format(sizeInBytes/SPACE_KB) + " KB";
                } else if ( sizeInBytes < SPACE_GB ) {
                    return nf.format(sizeInBytes/SPACE_MB) + " MB";
                } else if ( sizeInBytes < SPACE_TB ) {
                    return nf.format(sizeInBytes/SPACE_GB) + " GB";
                } else {
                    return nf.format(sizeInBytes/SPACE_TB) + " TB";
                }
            } catch (Exception e) {
                return sizeInBytes + " Byte(s)";
            }
    
        }
    

    I hope this may help you.