Faster Downlading a file and saving in SDCARD or storage in Android.

By | September 14, 2015

Here is a simple and faster way to download a file from the internet in Android.


package com.coderzheaven.downloadfile;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	        new Thread(new Runnable() {
			@Override
			public void run() {
				downloadFile("https://pbs.twimg.com/profile_images/2253481042/250x250_400x400.png", new File(Environment.getExternalStorageDirectory() + File.separator
						+ "coderzheaven.png"));
			}
		}).start();

	}

	private static void downloadFile(String url, File outputFile) {
		Log.i("ACT", "Path : " + outputFile.getAbsolutePath());
		try {
			URL u = new URL(url);
			URLConnection conn = u.openConnection();
			int contentLength = conn.getContentLength();

			DataInputStream stream = new DataInputStream(u.openStream());

			byte[] buffer = new byte[contentLength];
			stream.readFully(buffer);
			stream.close();

			DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
			fos.write(buffer);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			return; // swallow a 404
		} catch (IOException e) {
			return; // swallow a 404
		}
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *