Friday, April 6, 2012

Android: Simple file IO... Back to square 1...

Haven't been touching Android for a very long so I decided to spend a bit of time playing with it. And here's my first tutorial on Android.

Here are my codes for this application.
SimpleFileIOActivity.java
package zcs.simpleFileIO;

import java.util.Date;

import zcs.utility.io.FileIO;
import zcs.utility.io.FileIOResult;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class SimpleFileIOActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        FileIOResult myFile;
        //Create file data.txt
        //or you can try "zcs/tester/wonder/try.txt" 
        //as a file name and it will create the respective
        //folders and files
        myFile = FileIO.createFile("try.txt");
        //Grab the Text View on the layout
     TextView tempTxtView = (TextView)this.findViewById(R.id.txtOutput);
     String strOutput;
     String strToday = "";
     Date tempDate = new Date();
     //Create a string that has today's date
     strToday = tempDate.toString();
     
        if(myFile.get_exist() == 1)
        {
         //If file exist, get contents of file and display it
         strOutput = this.getString(R.string.str_exist);
         strOutput = strOutput.replace("{0}", 
           FileIO.readContentFromFile(myFile.get_file()));
        }else if(myFile.get_exist() == 0){
         //If file doesn't exist, show a different msg
         strOutput = this.getString(R.string.str_create);
        }else{
         //Error occurred
         strOutput = this.getString(R.string.str_error);
        }
        //Show the text base on the condition of the file.
        tempTxtView.setText(Html.fromHtml(strOutput));

        //Update the file with the latest date.
        if(myFile.get_exist() <= 1)
        {
         FileIO.writeContentIntoFile(myFile.get_file(), strToday);
        }
    }
}
FileIO.java <- file that handles all the IO functions
package zcs.utility.io;

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

import android.os.Environment;

public class FileIO {
 
 /**
  * Function that will create the specified file
  * name.
  * @param tempPath - path of the file you are 
  *       trying to access
  * @return FileIOResult Object
  *
  */ 
 public static FileIOResult createFile(String tempPath)
 {
  FileIOResult tempResult = new FileIOResult();
  //Check if the App has access to the External 
  //Storage first.
  boolean mExternalStorageWriteable = false;
  String state = Environment.getExternalStorageState();

  if (Environment.MEDIA_MOUNTED.equals(state)) {
      // We can read and write the media
      mExternalStorageWriteable = true;
  } else {
      // Something else is wrong. 
   // It may be one of many other states, but all we need
      // to know is we can neither read nor write
      mExternalStorageWriteable = false;
  }  
  //If we have access to the storage
  if(mExternalStorageWriteable)
  {
   String tempFilePath = tempPath;
   if(!tempFilePath.startsWith("/"))
   {
    tempFilePath = "/" + tempFilePath;
   }
         File root = Environment.getExternalStorageDirectory();
         File tempFile = new File(root + tempPath);
         //Check if file exist         
         if(!tempFile.exists())
         {
          //split the string and grab all the folders first 
          String[] strPathArray = tempFilePath.split("/");
          //Create all the folders first
          String strFolder = "";
          for(int i = 0; i < (strPathArray.length - 1); i ++)
       {
           strFolder = strFolder + "/" + strPathArray[i];
       }
       File sdDir = new File(root + strFolder);
          if(!sdDir.exists()){
           sdDir.mkdirs();
          }
          //Create File Path
    tempFile = new File(root + strFolder, 
         strPathArray[strPathArray.length - 1]);
         }
         try {
          //Check for file existence.
          if(tempFile.exists())
          {
           tempResult.set_exist(1);
          }else{
           tempResult.set_exist(0);
          }
          //If file doesn't exist, let's make one. 
          if(!tempFile.exists())
          {
           tempFile.createNewFile();
          }
   } catch (IOException e) {
    e.printStackTrace();
   }
         tempResult.set_file(tempFile);
  }else{
      tempResult.set_exist(2);
  }
  return tempResult;
 }

 /**
  *
  * Writing contents to the specified file.
  * Note: Use createFile(String) to gain access to the
  * file first. 
  * @param tempFile - File you are accessing
  * @return contents as a string
  */ 
 public static String readContentFromFile(File tempFile)
 {
  FileInputStream fis = null;    
  int ch;
     StringBuffer strContent = new StringBuffer("");
  try 
  {
   fis = new FileInputStream(tempFile);
      while((ch = fis.read()) != -1)
      {
       strContent.append((char)ch);
      }
  } catch (Exception e) 
  {
   e.printStackTrace();
  } finally
  {
            try
            {
             fis.close();
             fis = null;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
  }
  return strContent.toString();
 }


 /**
  * Writing contents to the specified file.
  * Note: Use createFile(String) to gain access to the
  * file first. 
  * @param tempFile - File you are accessing
  * @param value - value you are going to write
  *       in the file
  */ 
 public static void writeContentIntoFile(File tempFile, String value)
 {
  FileOutputStream fos = null;
  try 
  {
   fos = new FileOutputStream(tempFile);

   fos.write(value.getBytes(),0,value.getBytes().length);
   fos.flush();
  } catch (Exception e) 
  {
   e.printStackTrace();
  } finally
  {
            try
            {
                fos.close();
                fos = null;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
  }
 }
}
FileIOResult.java <- Object that stores the results of the File IO
package zcs.utility.io;

import java.io.File;

public class FileIOResult { 
 private int _exist = 0;
 private File _file = null;

 /**
  * Used to check for the existance of the file.  
  * @return one of the below integer (0-2)
  *  
0 - file does not exist and it will
  *    be created
  *  
1 - file exist
  *  
2 - Error
  */ 
 public int get_exist() {
  return _exist;
 }

 public void set_exist(int _exist) {
  this._exist = _exist;
 }

 public File get_file() {
  return _file;
 }

 public void set_file(File _file) {
  this._file = _file;
 }

 public FileIOResult() {
 }
}

AndroidManifest.xml <- Take note of the permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="zcs.simpleFileIO"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".SimpleFileIOActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

This screen will be shown
if file doesn't exist.
This screen will be shown
if file exist.

* Click here for the source files.

No comments:

Post a Comment