Read/Write Text File/Data in Android example code


package com.test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private static final String TAG = MainActivity.class.getName();
	private static final String FILENAME = "myFile.txt";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String textToSaveString = "Hello Android";
        
        writeToFile(textToSaveString);
        
        String textFromFileString =  readFromFile();
        
        if ( textToSaveString.equals(textFromFileString) ) 
        	Toast.makeText(getApplicationContext(), "both string are equal", Toast.LENGTH_SHORT).show();
        else 
        	Toast.makeText(getApplicationContext(), "there is a problem", Toast.LENGTH_SHORT).show();
    }
    
	private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        } 
		
	}

	private String readFromFile() {
		
        String ret = "";
        
        try {
            InputStream inputStream = openFileInput(FILENAME);
            
            if ( inputStream != null ) {
            	InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            	String receiveString = "";
            	StringBuilder stringBuilder = new StringBuilder();
            	
            	while ( (receiveString = bufferedReader.readLine()) != null ) {
            		stringBuilder.append(receiveString);
            	}
            	
            	inputStream.close();
            	ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
        	Log.e(TAG, "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e(TAG, "Can not read file: " + e.toString());
		}

        return ret;
	}
}
About these ads

23 thoughts on “Read/Write Text File/Data in Android example code

  1. @gu
    nope. you don’t need to put any files in anywhere
    the problem is, you would like to write some data in a file and read it back
    if you use the above code, a file will be created in your app sandbox (other app does not have access to it) and you can read it from there

  2. Thx this helped me a lot!
    Only got one problem:
    When i try to read my data and send it to a TextView it only shows the latest string
    hope you can help me

  3. i have two activities:
    in the first, i want to write text from an EditText to a file like in your sample
    it looks like this:

    private OnClickListener btn=new OnClickListener() {
    public void onClick(View v){

    String name = etWinner.getText().toString();
    writeToFile(name);
    startActivity(new Intent(SubmitActivity.this, MainActivity.class));

    }
    };

    private void writeToFile(String data){
    String newline=”\r\n”;
    try {

    OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(HIGHSCORE, Context.MODE_PRIVATE));
    oswName.write(newline);
    oswName.write(data);
    oswName.close();
    }
    catch (IOException e) {
    Log.e(TAG, “File write failed: ” + e.toString());
    }
    }

    in the second activity i try to read the stored data and write it to a textView:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_highscore);

    btn1 = (Button)findViewById(R.id.buttonBack);
    btn1.setOnClickListener(btn);

    String winners = readFromFile();
    TextView tvNames=(TextView)findViewById(R.id.textViewNames);
    tvNames.setText(winners);

    }

    private String readFromFile(){
    String ret = “”;

    try {
    InputStream inputStream = openFileInput(HIGHSCORE);

    if ( inputStream != null ) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String receiveString = “”;
    StringBuilder stringBuilder = new StringBuilder();

    while ( (receiveString = bufferedReader.readLine()) != null ) {
    stringBuilder.append(receiveString);
    }

    ret = stringBuilder.toString();

    inputStream.close();
    }
    }
    catch (FileNotFoundException e) {
    Log.e(TAG, “File not found: ” + e.toString());
    } catch (IOException e) {
    Log.e(TAG, “Can not read file: ” + e.toString());
    }
    return ret;

    }

    basically its just your code so i don’t get why it doesn’t work :(

    thx for the help

    Satanta

  4. edit:
    by latest string i mean it only shows the last data stored, not all the data
    like – let’s say String is “american pie”, it shows “american pie”
    if i store another string it just shows this one, probably overwrites “american pie”

  5. yes, previous data is going to be overwritten by the new data, thats how it supposed to work.

    if you want to save the data then you need to open the file in MODE_APPEND, not MODE_PRIVATE (line #40)

    For more information:
    openFileOutput

  6. Tnx this is great but i have one question!

    J have 3 variables, a,b and c. I want to save them like 0 10 30 etc. (30 is max) and when open application again i want to read them again so b and c wouldnt be 0 they will be 10 and 30 and use that. How J can save them in that way and read them? tnx a lot!

  7. Hi thanks for your post..but after saving data into myFile.txt…i want see where that myFile.txt file is saved either sd card or in apps assets folder or some where else…

  8. I am doing Payment tracker project. My doubt is, if i am giving a number/value then i am pressing a button how to store that number/value in internal phone memory with a mark not send and when the internet is connected it will automatically send to the url given in program(that means post request)and the mark will change after the number/value is send basically it is about JSON Parsing. Can u Help me Plz!

  9. when i execute this i am not getting where file is saved. Can you help me by giving procedure to execute this? when i execute this its showing “hello world”. I guess file is not getting created.I am getting error in “R.layout.main”. please can you give a steps to execute this?

  10. Hello, i’m so excited to look into your post. But I have a question. that program is about read/write file in txt. How about to read/write file in .doc ?? please help me, Mr. thankyou :)

  11. Hi how do you load the text into a listview using simple adapter ?
    I want to append words from edit text one per line and save to text file …
    cat
    dog
    cow

    Than i want to load the text from the text file back as an array into listview ….Is that possible please help

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s