The following functions fetches the file contents from a remote location, stores it in a given directory with a given file name on the SDCard of the device

  1. public static void downloadFileToSDCard(String fileURL, String directory,String fileName)
  2. throws Exception {
  3.  
  4.         Log.d("downloadFfile : " + fileURL);
  5.         String RootDir = Environment.getExternalStorageDirectory() + File.separator + directory;
  6.         File RootFile = new File(RootDir);
  7.         RootFile.mkdir();
  8.         Log.d("directory made or there");
  9.         URL u = new URL(fileURL);
  10.         HttpURLConnection c = (HttpURLConnection) u.openConnection();
  11.         c.setRequestMethod("GET");
  12.         c.setDoOutput(true);
  13.         c.connect();
  14.         Log.d("connected");
  15.         FileOutputStream f = new FileOutputStream(new File(RootFile, fileName));
  16.         InputStream in = c.getInputStream();
  17.         byte[] buffer = new byte[1024];
  18.         int len1 = 0;
  19.         Log.d("got stream reading");
  20.         while ((len1 = in.read(buffer)) > 0) {
  21.                 Log.d("write read to buffer");
  22.                 f.write(buffer, 0, len1);
  23.         }
  24.         f.flush();
  25.         f.close();
  26.         in.close();
  27. }