Android write and read file


In this Android tip, I am going to show you how to write text and read text from a text file. Classes of java.io package that are used in Java to write data and read data from a file can also be used in Android. In java.io package, you can use FileWriter class to write text to a file. If you want to write line by line of text, you will wrap the FileWriter instance in a BufferedWriter. The BufferedWriter class has the newline() method that allows you to add a new line to the file. You can use the following constructors when creating instances of FileWriter and BufferedWriter:

- FileWriter(String filename) create an instance of FileWriter to write data to a specified file. It creates the file automatically for you if it does not exist.
- FileWriter(String filename, boolean append) create an instance of FileWriter to append data to a specified file or override the file. If you specify true value to the append parameter, you open the file to append text. Otherwise the file is overridden. It creates the file automatically for you if it does not exist.
- BufferedWriter(FileWriter instance) creates an instance of BufferedWriter.
The FileWriter and BufferedWriter class have the write() method that can be used to write a character, an array of characters, or a string to a file.

To read data from a text file, you use FileReader class. If you want to read the file line by line, you wrap the FileReader instance in BufferedReader. The FileReader class has the read() method that allows to read a character or an array of characters from the file. Here are the constructors of FileReader and BufferedReader classes:

- FileReader(String filename) creates an instance of FileReader to read data from a file.
- BufferedReader(FileReader instance) creates an instance of BufferedReader that allows you to read the file line by line by using the readLine() method.

Now to have an example application on writing to and reading from a text file, you create an Android project. Then in activity_main.xml file, you add two Buttons, an EditText, and a TextView as shown below.



<LinearLayout 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"
   android:orientation="vertical"
   tools:context="com.example.writereadfile" >
  
   <EditText
android:id="@+id/txtedit"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Type your text..."
android:singleLine="false"
/>
<LinearLayout
android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"

   >
  <Button
android:id="@+id/btsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="writeFile"
/>
  
  <Button
android:id="@+id/btread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:onClick="readFile"
/>
</LinearLayout>
<TextView
android:id="@+id/txtview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"
/>

</LinearLayout>


In the MainActivity class, you write code of the writeFile() and readFile() methods as shown below.

package com.example.writereadfile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity{

private EditText editText;
private TextView textView;
private final String filename=Environment.getExternalStorageDirectory()+"/txtfile.txt";
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     editText=(EditText)findViewById(R.id.txtedit);
     textView=(TextView)findViewById(R.id.txtview);
   }

   public void writeFile(View view){
   FileWriter fw=null;
   BufferedWriter bw=null;
   try {
fw=new FileWriter(filename,true);
bw=new BufferedWriter(fw);
bw.write(editText.getText().toString());


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   finally{
   try {
   if(bw!=null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   }
   }
  
   public void readFile(View view){
   FileReader fr=null;
   BufferedReader br=null;
   try {
fr=new FileReader(filename);
br=new BufferedReader(fr);
String line,text="";
while((line=br.readLine())!=null){
if(text.equals(""))
text=line;
else
text+="\r\n"+line;
}
textView.setText(text);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   finally{
   try {
   if(br!=null)
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
   }
   }

}


Before running the example application, don't forget to declare WRITE_EXTERNAL_STORAGE permission in AndroidManifest.xml file of your project.

Android-write-and-read-file

Posted by: Dara | post date: 12-19-2014 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.