Loading ...

Reading and Writing to a file in android | CodeAsp.Net

Reading and Writing to a file in android

 /5
0 (0votes)

We will use the standard java IO classes and methods to read and write to a file in android.

To read and write to a file we will use the Mode.Private method.

Important:

//File name 
String file_name = “Test_File”;

// Create a new output file stream 
FileOutputStream fileos = openFileOutput(file_name, Context.MODE_PRIVATE);

// Create a new file input stream.
FileInputStream fileis = openFileInput(My_FILE_NAME);

1. Create an android studio project and name it as "Read_Write_File", and set the company domain as "codeasp.read_write_file.com". Click next.

2. Now select the minimum SDK as 18(Jelly Bean 4.3) and leave all other fields as they are and click next.

3. Select the activity as Blank Activity and click next.

4. Leave all the fields as default and click next.

5. Open your "acitivity_main.xml" file from the layout file. Here we will have to create a basic layout that we will use to read and write to the file.

6. In the "activity_main.xml" file add the following code:

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">


<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:ems="10"
android:inputType="textMultiLine"
android:lines="10" />

<Button
android:id="@+id/write_to_file"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/editText"
android:layout_alignParentStart="true"
android:layout_below="@+id/editText"
android:layout_marginTop="30dp"
android:onClick="Writing_data_File"
android:text="Write To File" />

<Button
android:id="@+id/to_reading_screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/write_to_file"
android:layout_alignParentStart="true"
android:layout_below="@+id/write_to_file"
android:onClick="To_Reading_Screen"
android:text="To Reading Screen" />
</RelativeLayout>

7. Now open your "MainActivity.java" file so that we can write code to write to the file. We will use the File "FileOutputStream" and "OutputStreamWriter" to write to the file.

Add the following code:

// writing data to a file
	public void Writing_data_File(View v) {
		try {
			FileOutputStream fileOutputStream=openFileOutput("Test_File", MODE_PRIVATE);
			OutputStreamWriter writer=new OutputStreamWriter(fileOutputStream);
			writer.write(data_to_add.getText().toString());
			writer.close();
			
			//Tell user that the file has been saved
			Toast.makeText(getBaseContext(), "Your file has been saved successfully!",
			Toast.LENGTH_LONG).show();
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}

Before adding the above code you need to bind the "edittext" to the java file.

To do that, add the following code below the class name and above the "onCreate" method:

EditText data_to_add;

In the onCreate method add the following code to bind it:

data_to_add=(EditText)findViewById(R.id.editText);

After adding all the data your file looks like this:

package com.read_write_file.codeasp.read_write_file;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
EditText data_to_add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

data_to_add = (EditText) findViewById(R.id.editText);
}

// writing data to a file
public void Writing_data_File(View v) {
try {
FileOutputStream fileOutputStream = openFileOutput("Test_File", MODE_PRIVATE);
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
writer.write(data_to_add.getText().toString());
writer.close();

//Tell user that the file has been saved
Toast.makeText(getBaseContext(), "Your file has been saved successfully!",
Toast.LENGTH_LONG).show();

} catch (Exception e) {
e.printStackTrace();
}
}

// writing data to a file
public void To_Reading_Screen(View v) {
Intent i = new Intent(this, ReadingScreen.class);
startActivity(i);

}
}

8. On clicking the "Write To File" button, all the data will be written to the file.

9. Now create a new Java file and a Xml file and name them as "ReadingScreen.java" and "reading_screen" respectively.

10. In your file "reading_screen" add the following code to give it a basic layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/to_writing_screen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:onClick="To_Writing_Screen"
        android:text="To Writing Screen" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/to_writing_screen"
        android:layout_alignParentStart="true"
        android:onClick="Read_Data"
        android:text="Read Data" />
</RelativeLayout>

11. Next, open the file ReadingScreen.java so that we can write code to read from the file. Here we will use the File "FileInputStream" and "InputStreamReader" to read from the file.

Add the following code:

// Read data from file
    public void Read_Data(View v) {
        try {
            FileInputStream fileInputStream = openFileInput("Test_File");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);

            char[] inputBuffer = new char[READ_BLOCK_SIZE];
            String s = "";
            int charRead;

            while ((charRead = inputStreamReader.read(inputBuffer)) > 0) {
                // char to string conversion
                String readstring = String.copyValueOf(inputBuffer, 0, charRead);
                s += readstring;
            }
            inputStreamReader.close();
            data_to_read.setText(s);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Before adding the above code you need to bind the "TextView" to the java file.

To do that, add the following code below the class name and above the "onCreate" method:

TextView data_to_read;

In the onCreate method add the following code to bind it:

data_to_read = (TextView) findViewById(R.id.textView);

After adding all the data your file looks like this:

package com.read_write_file.codeasp.read_write_file;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.FileInputStream;
import java.io.InputStreamReader;


/**
 * Created by Ravi on 17/08/15.
 */
public class ReadingScreen extends AppCompatActivity {
    TextView data_to_read;
    static final int READ_BLOCK_SIZE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        data_to_read = (TextView) findViewById(R.id.textView);
    }

    // Read data from file
    public void Read_Data(View v) {
        try {
            FileInputStream fileInputStream = openFileInput("Test_File");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);

            char[] inputBuffer = new char[READ_BLOCK_SIZE];
            String s = "";
            int charRead;

            while ((charRead = inputStreamReader.read(inputBuffer)) > 0) {
                // char to string conversion
                String readstring = String.copyValueOf(inputBuffer, 0, charRead);
                s += readstring;
            }
            inputStreamReader.close();
            data_to_read.setText(s);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // writing data to a file
    public void To_Writing_Screen(View v) {
        Intent i = new Intent(this, MainActivity.class);
        startActivity(i);

    }
}

12. Now we need to mention the activity we created above in the manifest file. To do that, add the following code to the manifest file:

<activity
android:name=".ReadingScreen" android:label="@string/app_name"/>

After adding the code your manifest file will look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.read_write_file.codeasp.read_write_file">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ReadingScreen"
            android:label="@string/app_name" />
    </application>

</manifest>

13. Now run the application on your phone or the emulator.

Application Screen Shots:

          

Comments (no comments yet)

Top Posts