Wednesday, 18 November 2015

Download file fast and then store SDCARD

Hi guys i am going to explain download file from server and then store in sdcard. it's very simple refer the below code.


package com.readcontact;

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

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;


public class Downloadimage extends ActionBarActivity {

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

        new Thread(new Runnable() {
            @Override            public void run() {
                downloadFile("http://www.tivix.com/uploads/blog_pics/Android-logo.png", new File(Environment.getExternalStorageDirectory() + File.separator                        + "test.png"));
            }
        }).start();
    }

    private static void downloadFile(String url, File outputFile) {
        Log.i("ACT", "Path : " + outputFile.getAbsolutePath());
        Log.w("ASHOK MSG","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        }
    }

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_downloadimage, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

No comments:

Post a Comment