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 :-)

.

No comments:

Post a Comment