Android Lesson 4: File manipulation


We create some examples for learn how to manipulate files with Android.

Example 1: Work with internal storage

Step 1: create new project
Step 2: Edit file content_main.xml
Create some textviews and buttons, add the code:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TUTORIALSPOTS.COM"
        android:id="@+id/textView"
        android:textSize="30dp"
        android:textColor="#FF0000"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="File: tutorialspots.txt"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check File Exist"
        android:id="@+id/button"
        android:layout_above="@+id/button2"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write File"
        android:id="@+id/button2"
        android:layout_above="@+id/button3"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read File"
        android:id="@+id/button3"
        android:layout_centerVertical="true"
        android:layout_alignStart="@+id/button2" />

android file manipulation

Step 3: Edit file MainActivity.java:
Edit class MainActivity:

package com.tutorialspots.file;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

public class MainActivity extends AppCompatActivity {
    public String filename = "tutorialspots.txt";
    public String string = "Welcome to Tutorialspots";
    public File file;

    public Button button;
    public Button button2;
    public Button button3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Toast.LENGTH_LONG).show();
            }
        });

        file = getFileStreamPath(filename);

        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(file.exists()){
                    Toast.makeText(getApplicationContext(), "This file exists!", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "This file doesn't exist!", Toast.LENGTH_LONG).show();
                }
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
                    fos.write(string.getBytes());
                    fos.close();
                    Toast.makeText(getApplicationContext(), "This file has been wroten!", Toast.LENGTH_LONG).show();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String line;
                    String content = "";
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    while((line = br.readLine())!=null){
                        content += line;
                    }
                    Toast.makeText(getApplicationContext(), content, Toast.LENGTH_LONG).show();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
..............
}

Now, we can test this application.
Step 4: Run app

check file exists

Conclusion for Example 1:

To check file exists:

file = getFileStreamPath(filename);
if(file.exists()){
                    // File exists
                }else{
                    // File doesn't exist
                }

To write file:

try {
                    FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
                    fos.write(string.getBytes());
                    fos.close();
                    //Do anything
                }catch (Exception e){
                    //Error
                }

or we can use this method:

            FileWriter writer = new FileWriter(getFileStreamPath(filename));
            BufferedWriter bw = new BufferedWriter(writer);
            bw.write(string);
            bw.flush();
            bw.close();

To read file:

try {
                    String line;
                    String content = "";
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    while((line = br.readLine())!=null){
                        content += line;
                    }
                    //Do anything
                }catch (Exception e){
                    //Error
                }

Leave a Reply