download File from Url - Android java.net

Android examples for java.net:URL

Description

download File from Url

Demo Code

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

public class Main {

  public static File downloadFile(String sUrl) {
    try {//www  .ja  v a2 s  .  c o  m
      URL url = new URL(sUrl);
      int slashIndex = sUrl.lastIndexOf('/');
      String fileName = sUrl.substring(slashIndex + 1);

      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

      // set up some things on the connection
      urlConnection.setRequestMethod("GET");
      // http://stackoverflow.com/questions/9365829/filenotfoundexception-for-httpurlconnection-in-ice-cream-sandwich
      // urlConnection.setDoOutput(true);

      // and connect!
      urlConnection.connect();
      // this will be used in reading the data from the internet
      InputStream inputStream = urlConnection.getInputStream();

      // this is the total size of the file
      int totalSize = urlConnection.getContentLength();
      // variable to store total downloaded bytes
      int downloadedSize = 0;

      // create a buffer...
      byte[] buffer = new byte[1024];
      int bufferLength = 0; // used to store a temporary size of the buffer

      // File dir = Environment.getExternalStorageDirectory();
      File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
      File file = new File(dir, fileName);
      FileOutputStream fileOutput = new FileOutputStream(file);

      while ((bufferLength = inputStream.read(buffer)) > 0) {
        fileOutput.write(buffer, 0, bufferLength);
        downloadedSize += bufferLength;
      }
      fileOutput.close();
      return file;
    } catch (MalformedURLException e) {
      processException(e);
    } catch (IOException e) {
      processException(e);
    }
    return null;
  }

  public static void processException(Exception ex) {
    Log.w("TAG", ex.getMessage(), ex);

  }

}

Related Tutorials