Can Android Example Use Scanner to Read Text Files

Today we are going to code about a sample app with some operations I usually play with text files in my Android applications. These operations would include creating, reading, updating,and deleting text files. I find these operations actually useful when I have to shop some data temporarily, creating some log files, or store some actual content simply like what evernote does, come across screenshot below.

Working with Text Files in Android

For apps like Evernote, storing some user content information on the device disk or sdcard is okay, some reason include, the device is a personal belongings, it is always with you. Some other reason is, the data is "syncable". If you think you lot lost some data in the device (like accidental file deletion), you tin can e'er but sync and your information will come back to life in your device. I honey cloud computing!
Below is the lawmaking download, basic CRUD codes and a Sample Application.

Download code here

Sample Awarding

txtlayout

In this sample awarding, when a user clicked a button:

  • Create Text File – a folder in your sdcard will be created with an empty text file in it (sdcard/MikeDalisayFolder/coan_log_file.txt)
  • Read Text File – the contents of coan_log_file.txt text file will exist shown in the screen, yous should click the update text file push first so information technology will have contents.
  • Update Text File – it volition update our text file with two lines of text.
  • Delete Text File – information technology will delete our text file, of course. :)
  • Nosotros will apply a TextFileHelper form I created. I believe you lot tin see more than useful techniques here like code re-usability and validation.

src/com.your.parcel/TextFileHelper.java lawmaking – This class contains our text file Grime codes.

package com.example.textfilesexample; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter;  import android.content.Context; import android.widget.Toast;  /*  * This class is for text file Crud.  * Yous tin can merely make flashMessage() a comment if you do not need it.  */ public class TextFileHelper {      // context is used for toasts     Context mContext;      /*      * Constructor      */     public TextFileHelper(Context mContext) {         this.mContext = mContext;     }      /*      * Create a text file.      */     public void createTextFile(String actualFile) {         attempt {              File file = new File(actualFile);              if (file.exists()) {                 flashMessage("Text file already exists.");             } else {                  // create the text file                 if (file.createNewFile()) {                     flashMessage("Text file was created.");                 } else {                     flashMessage("Unable to create text file.");                 }              }          } catch (NullPointerException east) {             e.printStackTrace();         } grab (Exception eastward) {             eastward.printStackTrace();         }     }      /*      * Read a text file.      */     public String readTextFile(String actualFile) {          Cord contents = "";          endeavor {              // Go the text file             File file = new File(actualFile);              // check if file is non empty             if (file.exists() && file.length() != 0) {                  // read the file to get contents                 BufferedReader br = new BufferedReader(new FileReader(file));                 String line;                  while ((line = br.readLine()) != zilch) {                     // shop the text file line to contents variable                     contents += line + "northward";                 }              } else {                 flashMessage("Unable to read. File may be missing or empty.");             }          } catch (NullPointerException e) {             e.printStackTrace();         } grab (Exception east) {             e.printStackTrace();         }          return contents;     }      /*      * Update a text file.      */     public void updateTextFile(String actualFile, Cord contents) {         endeavour {              File textFile = new File(actualFile);              if (textFile.exists()) {                  // set to truthful if you desire to append contents to text file                 // set to false if you want to remove preivous content of text                 // file                 FileWriter textFileWriter = new FileWriter(textFile, false);                  BufferedWriter out = new BufferedWriter(textFileWriter);                  // create the content string                 String contentString = new String(contents);                  // write the updated content                 out.write(contentString);                 out.close();                  flashMessage("File was updated.");              } else {                 flashMessage("Cannot update. File does non be.");             }          } catch (NullPointerException e) {             e.printStackTrace();         } catch (Exception e) {             e.printStackTrace();         }     }      /*      * Delete a text file.      */     public void deleteTextFile(String actualFile) {         try {              File file = new File(actualFile);              if (file.exists()) {                  if (file.delete()) {                     flashMessage("Text file was deleted!");                 } else {                     flashMessage("Unable to delete text file.");                 }              } else {                 flashMessage("Unable to delete. File does non exist.");             }          } catch (NullPointerException e) {             e.printStackTrace();         } catch (Exception e) {             due east.printStackTrace();         }     }      /*      * Method to create path where our text file volition be created.      */     public void createPath(String filePath) {         effort {              File file = new File(filePath);              if (file.isDirectory()) {                 flashMessage("Path exists.");             }              // create the directory             else {                 if (file.mkdirs()) {                     flashMessage("Path was created.");                 } else {                     flashMessage("Unable to create path.");                 }              }          } catch (NullPointerException e) {             e.printStackTrace();         } catch (Exception east) {             e.printStackTrace();         }     }      /*      * Only an extra method for displaying toasts.      */     public void flashMessage(String customText) {         try {              Toast.makeText(mContext, customText, Toast.LENGTH_SHORT).show();          } catch (NullPointerException east) {             eastward.printStackTrace();         } catch (Exception eastward) {             e.printStackTrace();         }     }  }        

src/com.your.package/MainActivity.java code

packet com.instance.textfilesexample; import android.os.Bundle; import android.os.Surround; import android.view.View; import android.widget.TextView; import android.app.Activeness;  public class MainActivity extends Activity {      // our TextFileHelper     TextFileHelper TextFileH;      // where our text file will be created     String filePath = Environment.getExternalStorageDirectory() + "/MikeDalisayFolder/";          // name of our text file     String fileName = "coan_log_file.txt";          // filePath and fileName combined     String actualFile = filePath + fileName;          TextView contentsTextView;          @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          try {              // initialize our TextFileHelper here             TextFileH = new TextFileHelper(MainActivity.this);              // first, make certain the path to your text file is created             TextFileH.createPath(filePath);                          // so we tin can show file contents to the user             contentsTextView = (TextView) findViewById(R.id.contentsTextView);                          // here is the actual button listener             View.OnClickListener handler = new View.OnClickListener() {                  public void onClick(View v) {                      // we will use switch argument and just                     // get the button's id to make things easier                     switch (five.getId()) {                      // when create push was clicked                     case R.id.createBtn:                         TextFileH.createTextFile(actualFile);                         contentsTextView.setText("");                         break;                      // when read button was clicked                     case R.id.readBtn:                         Cord contents = TextFileH.readTextFile(actualFile);                         contentsTextView.setText(contents);                         break;                      // when update button was clicked                     case R.id.updateBtn:                         TextFileH.updateTextFile(actualFile, "Mike is so handsome!nNew line here!");                         contentsTextView.setText("");                         intermission;                      // when edit button was clicked                     case R.id.deleteBtn:                         TextFileH.deleteTextFile(actualFile);                         contentsTextView.setText("");                         break;                     }                 }             };              // we will get the button views and set the listener (handler)             findViewById(R.id.createBtn).setOnClickListener(handler);             findViewById(R.id.readBtn).setOnClickListener(handler);             findViewById(R.id.updateBtn).setOnClickListener(handler);             findViewById(R.id.deleteBtn).setOnClickListener(handler);          } catch (NullPointerException east) {             eastward.printStackTrace();         } catch (Exception due east) {             e.printStackTrace();         }     }  }        

AndroidManifest.xml code – the permission will be WRITE_EXTERNAL_STORAGE

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    bundle="com.example.textfilesexample"    android:versionCode="ane″    android:versionName="1.0″ >     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />        <uses-sdk        android:minSdkVersion="8″        android:targetSdkVersion="15″ />      <application        android:icon="@drawable/ic_launcher"        android:characterization="@string/app_name"        android:theme="@way/AppTheme" >         <activity            android:proper name=".MainActivity"            android:characterization="@string/title_activity_main" >             <intent-filter>                 <action android:name="android.intent.activeness.MAIN" />                  <category android:proper name="android.intent.category.LAUNCHER" />             </intent-filter>         </action>     </awarding>  </manifest>        

res/layout/activity_main.xml lawmaking

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >     <Button        android:id="@+id/createBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="truthful"        android:text="Create Text File" />      <Push button        android:id="@+id/readBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/createBtn"        android:text="Read Text File" />      <Button        android:id="@+id/updateBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/readBtn"        android:text="Update Text File" />      <Button        android:id="@+id/deleteBtn"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/updateBtn"        android:text="Delete Text File" />      <TextView        android:id="@+id/contentsTextView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/deleteBtn"        android:text="Text file contents should be here." />  </RelativeLayout>        

Some other notes:

  • You can create a text file with a different extension name and yet it will all the same be readable by your programme. For example, you tin brand a file proper name like "my_file.coan", evernote does "content.enml". That file will non be hands read in the device since there are no app that can open up a file with that extension. Your text file will be easily ignored by the users.
  • If you want to update a specific line of your text file, yous have to read it first, track the line number, insert the updated line and use the lawmaking above.

Can Android Example Use Scanner to Read Text Files

Source: https://www.androidcode.ninja/working-with-text-files-in-android/

0 Response to "Can Android Example Use Scanner to Read Text Files"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel