Downloading a file programatically, from your Android application

I’m  lazy to redo work..So, presenting working code right infront of you :-).I think comments are sufficient to explain how the things are working....



package org.sample.example.download;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.util.Log;

public class DownLoadManager {

      //MAKE SURE YOU HAVE SET INTERNET PERMISSION ....
     
public void startDownLoad(Context context, String sourceUrl,String destinationPath)
      {          
new DownLoadFileThread(context, sourceUrl, destinationPath).start();
      }
     
      private static class DownLoadFileThread extends Thread{
           
            Context context=null;
            String sourceUrl=null;
            String destinationPath=null;
           
            /*
             * Make sure sourceUrl ends with a file to download and not a folder!.
             *  Same with destinationPath.
             *  Ex:
             * 
             *  sourceUrl="http://www.tempurl.com/image1.jpg"
             *  destinationPath="data/data/<package-name>/files/image1.jpg"
             */
public DownLoadFileThread(Context context, String sourceUrl,String destinationPath)
            {
                  this.context=context;
                  this.sourceUrl=sourceUrl;
                  this.destinationPath=destinationPath;
            }
           
            @Override
            public void run()
            {
                  downLoadFileFromServer();
            }

           
            public boolean downLoadFileFromServer()
            {
                  Log.v("DEBUG", "sourceUrl: "+sourceUrl);
                  Log.v("DEBUG", "destinationPath: "+destinationPath);             
                 
                  InputStream urlInputStream=null;
                 
                  URLConnection urlConnection ;
                 
            try
              {
                  //Form a new URL
                  URL finalUrl =new URL(sourceUrl);
                 
                  urlConnection = finalUrl.openConnection();  

                  //Get the size of the (file) inputstream from server..
                  int contentLength=urlConnection.getContentLength();
                 
                  Log.d("1URL","Streaming from "+sourceUrl+ "....");               
      DataInputStream stream = new DataInputStream(finalUrl.openStream());
                 
      Log.d("2FILE","Buffering the received stream(size="+contentLength+") ...");
                  byte[] buffer = new byte[contentLength];
                  stream.readFully(buffer);
                  stream.close();
      Log.d("3FILE","Buffered successfully(Buffer.length="+buffer.length+")...."); 
                 
                  if (buffer.length>0)
                  {
                           try
                           {                   
                                 Log.d("4FILE","Creating the new file..");                                 
                                 FileOutputStream fos = context.openFileOutput(destinationPath, Context.MODE_PRIVATE);
Log.d("5FILE","Writing from buffer to the new file..");
                               fos.write(buffer);
                               fos.flush();
                               fos.close();
                               Log.d("6.1FILE","Created the new file & returning 'true'.."); 
                               return true;
                           }
                           catch (Exception e)
                           {
                                 // TODO Auto-generated catch block
                                 Log.e("7ERROR", "Could not create new file(Path="+destinationPath+") ! & returning 'false'.......");
                                 e.printStackTrace();
                                 return false;
                                 /*Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();*/
                           }
                  }
                  else
                  {           
                        //Could not download the file...
Log.e("8ERROR", "Buffer size is zero ! & returning 'false'.......");
                        return false;
                  }
              }
            catch (Exception e)
              {
Log.e("9ERROR", "Failed to open urlConnection/Stream the connection(From catch block) & returning 'false'..");
                  System.out.println("Exception: " + e);
                  e.printStackTrace();
                  return false;
              }
              finally
              {
                  try
                  {
                        Log.d("10URL", "Closing urlInputStream... ");
                      if (urlInputStream != null) urlInputStream.close();
                     
                  }
                  catch (Exception e)
                  {
Log.e("11ERROR", "Failed to close urlInputStream(From finally block)..");
                  }
              }      
            }      
      }
             
}



Once done, you may find your file under DDMS>File Explorer>data/data/package_name/files/

I admit that this isn’t a better way to handle downloading files over internet! You should handle such things asynchronously.  I will be shortly posting the same over here...Till then keep visiting ;-)


Happy coding guys :-)


Writing-to and Reading-from a file in Android

I’m  lazy to redo work..So, presenting working code right infront of you :-).I think comments are sufficient to explain how the things are working....



package org.sample.example.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;

public class ReadWriteFileManager {
     
     
       public String readFromFile(Context context,String sourceFileName)
       {
             /*
              * Reading will be file type specific..
              * Here I'm considering text file alone..
              *
              */
            FileInputStream fis=null;
            InputStreamReader isr = null;
           
            char[] inputBuffer=null;
            String file_content = null;
           
            try
            {   
                  //As this requires full path of the file...
                  //i.e data/data/package_name/files/your_file_name
                  File sourceFile=
newFile(context.getFilesDir().getPath()
+File.separator+sourceFileName);

                  if(sourceFile.exists())
                  {                      
                        //Probably you will get an exception if its
//a huge content file..
                        //I suggest you to handle content here
//itself, instead of
                        //returning it as return value..
                        inputBuffer=new char[(int) sourceFile.length()];
                 
                        fis=context.openFileInput(sourceFileName);                 
                       
                        isr = new InputStreamReader(fis);                    
                        isr.read(inputBuffer);
                       
                        file_content = new String(inputBuffer);                    
                                                           
                        try
                        {    
                              isr.close();
                              fis.close();
                        }
                        catch (IOException e)
                        {    
                              e.printStackTrace();
                        }
                  }
                 
            }
            catch (Exception e)
            {    
                  e.printStackTrace();
                  file_content=null;
            }
                 
            return file_content;
          }
         
         
public boolean writeToFile(Context context,
byte [] contentToWrite,String destinationFileName)
      {
            FileOutputStream fos=null;
            boolean retValue=false;
            try
            {
                  //Note that your file will be created and stored
                  //under the path: data/data/your_app_package_name/files/
fos=context.openFileOutput(destinationFileName, Context.MODE_PRIVATE);
                 
                  //Note that we are not buffering of contents to write..
                  //So, this will work best for files with less content....
                  fos.write(contentToWrite);
                  //Successfully completed writing..
                  retValue=true;   
                  try
                  {
                        fos.flush();
                        fos.close();
                  }
                  catch (IOException e)
                  {                      
                        e.printStackTrace();
                  }
            }
            catch (Exception e)
            {    
                  //You can catch exceptions specifically for low mem,
                  //file cant be created, and so on..
                  e.printStackTrace();
                  //Failed to write..
                  retValue=false;
            }
                 
            return retValue;       
      }

}

Sample code snippets of how you may use above class is as shown below:

final String TEMP_FILE_NAME="temp.txt";
String contentToWrite="THIS IS THE CONTENT TO WRITE!";

Log.d("DEBUG","Instantiating ReadWriteManager..");

ReadWriteFileManager readWriteFileManager=new ReadWriteFileManager();   

      Log.d("DEBUG","Writing to file..."); 

readWriteFileManager.writeToFile(this,contentToWrite.getBytes(),
TEMP_FILE_NAME );

      Log.d("DEBUG","Reading from file..");

String contentRead= readWriteFileManager.readFromFile(this, TEMP_FILE_NAME);

      Log.d("DEBUG","Content read: "+contentRead);

Once done, you may find your file under DDMS>File Explorer>data/data/package_name/files/


Happy coding :-)

.