File Download From Server And Saving In External Memory


In this project we will be implementing a creating a code that downloads any kind of file from the server and saves it on your Android Device.

Using our personal computer as a host, we have already created a localHost server. In server a file named MyTextFile.txt is located. We will attempt to download the text file in our Android device and save it in external memory. 


Following is the code to download the file. 


AndroidManifest.xml:

Adding permissions for Internet and External storage access in manifest file

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ourcoaching.filedownloader">
<uses-permission android:name="android.permission.INTERNET">uses-permission
>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>

manifest>


activity_main.xml:

Setting up a simple layout with two buttons and a textview

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ourcoaching.filedownloader">
<uses-permission android:name="android.permission.INTERNET">uses-permission
>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>

manifest>


MainActivity.java:


To download file, we have to read the inputstream and then save the stream to your device using FileOutputStream

package com.ourcoaching.filedownloader;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

private final String DEBUG_TAG="MAIN ",DEBUG_TAG2="PROGRESS ";
private TextView textView;
private Button DownloadButton,ShowButton;
public String filename="MyTextFile.txt";
public String url="http://192.168.0.6/kk/DownloadFilesAndroid/MyTextFile.txt";
public String ExtDir;
private MyAsynDownloader myAsynDownloader;

public Context context;
private ProgressDialog progressDialog;

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

DownloadButton=(Button)findViewById(R.id.button);
ShowButton=(Button)findViewById(R.id.button2);
textView=(TextView)findViewById(R.id.textv);

//ExtDir=Environment.getExternalStorageDirectory().toString();
File ext=getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
ExtDir=ext.toString();

context=MainActivity.this;
}

@Override
protected void onResume() {
super.onResume();

DownloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DownoadFilesNow();
}
});

ShowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ShpowFilesACTUAL();
}
});


}

private void DownoadFilesNow() {
myAsynDownloader =new MyAsynDownloader();
myAsynDownloader.execute(url,ExtDir,filename);
}

private void ShpowFilesACTUAL() {
File ext=getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
ExtDir=ext.toString();

File file=new File(ExtDir+File.separator+filename);
Log.d(DEBUG_TAG+"new ext dir Read=",ExtDir);
Log.d(DEBUG_TAG+"new FIleRead=",file.toString());
Log.d(DEBUG_TAG+"new FileName=",filename);

InputStream inputStream;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;

if (file.exists()) {
try {
bufferedReader = new BufferedReader(new FileReader(file));

StringBuilder stringBuilder = new StringBuilder();

String receiveString;
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}

receiveString = stringBuilder.toString();
bufferedReader.close();

if (receiveString != null) {
textView.setText(receiveString);
Log.d(DEBUG_TAG + " recived=", receiveString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d(DEBUG_TAG+"n error1=",e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.d(DEBUG_TAG+"n error2=",e.toString());
}
}else Log.d(DEBUG_TAG+"file not ","exist");
}

private class MyAsynDownloader extends AsyncTask{

@Override
protected void onPreExecute() {
super.onPreExecute();

progressDialog=new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setIndeterminate(false);
progressDialog.show();

}

@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(Integer.parseInt(values[0]));
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.cancel();
}

@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
OutputStream outputStream;

File file;
byte[] buffer;
int length,len;

try {
url=new URL(strings[0]);
Log.d(DEBUG_TAG+"url=",url.toString());

httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.connect();

len=httpURLConnection.getContentLength();
Log.d(DEBUG_TAG+"len=",""+len);

inputStream = new BufferedInputStream(httpURLConnection.getInputStream(),
len);
Log.d(DEBUG_TAG+"after dos","executing");

String extdir=strings[1];
Log.d(DEBUG_TAG+"ext direc=",extdir);

String fname=strings[2];
Log.d(DEBUG_TAG+"filename=",fname);

file=new File(extdir+File.separator+fname);
Log.d(DEBUG_TAG+"file=",file.toString());

outputStream=new FileOutputStream(file);
buffer = new byte[1024];


int total = 0;
while ((length = inputStream.read(buffer))>0) {
total+=length;
publishProgress("" + (int) ((total * 100) / len));
outputStream.write(buffer, 0, length);
Log.d(DEBUG_TAG2+"progress","" + (int) ((total * 100) / len));

}

Log.d(DEBUG_TAG+"after","COMPLETE");


} catch (MalformedURLException e) {
Log.d(DEBUG_TAG+"error1=",e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d(DEBUG_TAG+"error2=",e.toString());
e.printStackTrace();
}
return null;
}
}


}


Output:


.


Download the code from GitHub




Related Tutorials