ATTENTION ATTENTION
gear.huuah.com has launched. Visit the shop at http://gear.huuah.com/. Lots of Photo Gear at the moment
ATTENTION ATTENTION
Itsplanned.com is just launched! - Task and project management made easy. Try it for free.

Create your own lists of things to do - arrange the order to do them - move them around - group them

No limitations - all free project management - try the free demo before signing up - demo: itsplanned.com
Android writing and reading files
01.04.2010

How to read and write files in you Android Application

When coding an application for the Android system, you will eventually need to store some data on the phones for later use. There are generally two ways of doing this – either in files or by using a SQLlite database.

Write to file

So your sitting there with your fancy newly developed application, but all your settings are going back to default values when the program starts. Why not just write the settings to a file and then read the file content when the application starts up.

To do this we need the OutputStream and OutputStreamReader, so lets import them like this:

import java.io.OutputStream;
import java.io.OutputStreamWriter;

Lets say the application has a save button somewhere and when this is clicked the onClick(View) is called. We can then add some code, to handle the file writing:

...
public void onClick(View view) {
...
// try to write the content
try {
  // open myfilename.txt for writing
  OutputStreamWriter out = new OutputStreamWriter(openFileOutput("myfilename.txt",0));
  // write the contents on mySettings to the file
  out.write(mySettings);
  // close the file
  out.close();
} catch (java.io.IOException e) {
  //do something if an IOException occurs.
}

There you go. The content from the mySettings variable should now be writting to the file myfilename.txt. How the settings come from the application to the mySettings variable is another subject and is not covered here.

Reading lines from a file

Now we have some data information writting to the myfilename.txt-file, that now exits on the Android device.

To read the information from the file, we need to the InputReader, InputReaderStream and BufferedReader, so just import them like this:

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

All we have to do now, is open the myfilename.txt for reading. This could be done like this:

...
  // try opening the myfilename.txt
  try {
    // open the file for reading
    InputStream instream = openFileInput("myfilename.txt");

    // if file the available for reading
    if (instream) {
      // prepare the file for reading
      InputStreamReader inputreader = new InputStreamReader(instream);
      BufferedReader buffreader = new BufferedReader(inputreader);
                
      String line;

      // read every line of the file into the line-variable, on line at the time
      while (( line = buffreader.readLine())) {
        // do something with the settings from the file
      }

    }
    
    // close the file again       
    instream.close();
  } catch (java.io.FileNotFoundException e) {
    // do something if the myfilename.txt does not exits
  }
...

We have now read the content of the myfilename.txt and made it available for the application.

To read more about this Android check out these books: here

16 Responses to “Android writing and reading files”

  1. Website Designer  Says:

    Hi,

    How to read and write files in you Android Application When coding an application for the Android system.

    Thanks,
    Allec

  2. alma Says:

    InputStream in

    not acceptable in IF condition

    and typo in variable name: input ~ inputreader

    did u run this code ever?

  3. weidberg Says:

    thank you very much for the great code,
    it works wonderful.
    after I write to the file “myfilename.txt”, where could i find it, when i’m running the android emulator?

    thenks

  4. js - huuah Says:

    #2 alma
    I have corrected the typo – thank you.

    Yes – I have tested the code, but it was part of some other tests, so I re-type the example code on my blog. To be honest I can not remember if I compiled and ran the code. That’s my mistake – sorry.

  5. Sambit Aryal Says:

    hello,
    how settings from application comes to mysettings? any help will be appreciated.

  6. sneha Says:

    where should I copied for read myfilename.txt in my application

  7. aftab Says:

    hi all is fine . but where can i find these files stored in android internal storage ? same how can I explore DB saved in android ?

  8. rosy Says:

    where could i find myfilename.txt, when i’m running the android emulator?

  9. Ripu Daman Says:

    When I read the value from the file how do i set it on the spinner(combobox)??
    so that whenever i open my app it shows the last selected value on the spinner & not the default value(the first value in the spinner)?

    Plzz help..It would be highly appreciated.!

  10. Gyubok Baik Says:

    Thank for the code! I greatly appreciate it.

    I have two questions. How would I transfer text from buffreader to a string?

    Also, it seems like “if (instream)” seems incomplete. What goes inside “if (…)”?

  11. Gyubok Baik Says:

    If I save the file, is it saved inside SD card? If not, how can I make it save inside SD card?

  12. Aditya Says:

    Its running without any error but content are not written in txt file.
    Any help….

    Thanks,
    Aditya

  13. Muhammad Mubashir Says:

    package com.example;

    import java.io.ByteArrayOutputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    import android.app.Activity;
    import android.content.res.AssetManager;
    import android.content.res.Resources;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;

    public class GetFromURLActivity extends Activity
    {
    TextView txtContent;
    String path;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try {
    //this is the file you want to download from the remote server

    /*path =”http://localhost:82/TextureTest01.apk”;*/
    path =”http://10.0.2.2:82/my.txt”;
    //this is the name of the local file you will create

    /*String targetFileName = “mynew”; // Omit extension.
    boolean eof = false;*/
    URL u = new URL(path);

    HttpURLConnection c = (HttpURLConnection) u.openConnection();

    c.setRequestMethod(“GET”);
    c.setDoOutput(true);
    c.connect();

    InputStream in = c.getInputStream();

    Log.e(“value”,in.toString());

    //Gets the instance of the asset manager
    AssetManager mngr=getAssets();

    //Resources resources = new Resources();
    //resources.getAssets().open(“my.txt”);
    //FileOutputStream f = new FileOutputStream(new File(“c:\\” + targetFileName));

    /*FileOutputStream f = this.openFileOutput(targetFileName,
    this.MODE_WORLD_READABLE);*/

    ByteArrayOutputStream bo = new ByteArrayOutputStream();

    byte[] buffer = new byte[1024];
    in.read(buffer); // Read from Buffer.
    bo.write(buffer); // Write Into Buffer.

    /*int len1 = 0;
    while ( (len1 = in.read(buffer)) != -1 )
    {
    //f.write(buffer,0, len1);
    bo.write(buffer,0, len1); // Write Into Buffer.
    }*/
    txtContent =(TextView)findViewById(R.id.textview);
    txtContent.setText(bo.toString());
    bo.close();
    //f.close();

    }
    catch (MalformedURLException e) {
    e.printStackTrace();
    //txtContent.setText(e.getMessage().toString());
    } catch (ProtocolException e) {
    e.printStackTrace();
    //txtContent.setText(e.getMessage().toString());
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    //txtContent.setText(e.getMessage().toString());
    } catch (IOException e) {
    e.printStackTrace();
    //txtContent.setText(e.getMessage().toString());
    }
    }
    String ReadFile(InputStream is)
    {
    ByteArrayOutputStream bo=new ByteArrayOutputStream();

    byte [] buffer=new byte[1024];

    try {
    is.read(buffer);
    bo.write(buffer);

    bo.close();
    is.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return bo.toString();
    }
    }

    // my Email id is muhammad.mubashir.bscs@gmail.com

  14. Kasper Says:

    Not saying writing settings to a file is wrong, but it’s really not the way Android does it.

    For persisting settings between app close and startups you should really use the “SharedPreferences” interface and override the onPause method of the activity:

    @override
    protected void onPause() {

    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();

    editor.putString(“username”, myUserName);
    }

    and then get the saved vars afterwards in the onCreate method.

  15. Sarwesh Suman Says:

    Hi,
    Can any one please tell that is there any library in android sdk which can be used to read write a MS word, excel?

  16. neel Says:

    the correct code for the reading, writing and deleting a file from internal storage from a device

    package com.halosys.android.internalstorage;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class WriteAFileToInternalStorageActivity extends Activity {

    private TextView mWrite;
    private TextView mRead;
    private Button write;
    public EditText et;
    private Button read;
    private Button delete;
    public static int i=1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    et=(EditText)findViewById(R.id.editText1);
    write = (Button)findViewById(R.id.button1);

    write.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    String FILENAME = “hello_file.txt”;
    String string = “hello world!”;

    FileOutputStream fos = null;
    try {
    fos = openFileOutput(FILENAME, Context.MODE_WORLD_WRITEABLE);

    } catch (FileNotFoundException e) {

    e.printStackTrace();
    }
    try {
    fos.write(string.getBytes());
    } catch (IOException e) {

    e.printStackTrace();
    }
    try {
    fos.close();
    } catch (IOException e) {

    e.printStackTrace();
    }
    }
    });

    read = (Button)findViewById(R.id.button2);

    /* read.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    try {

    File myFile = new File(“/hello_file.txt”);
    FileInputStream fis = new FileInputStream(myFile);
    BufferedReader myReader = new BufferedReader(
    new InputStreamReader(fis));
    String aDataRow = “”;
    String aBuffer = “”;
    StringBuffer fileContent = new StringBuffer(“”);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = fis.read(buffer)) != -1) {
    fileContent.append(new String(buffer));
    }

    et.setText(aBuffer);
    myReader.close();
    Toast.makeText(getBaseContext(),
    “Done reading SD ‘hello_file.txt’”,
    Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
    Toast.makeText(getBaseContext(), e.getMessage(),
    Toast.LENGTH_LONG).show();
    }
    }// onClick

    });*/

    read.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    String FILENAME = “hello_file.txt”;
    String string = “”;
    StringBuffer fileContent = new StringBuffer(“”);

    FileInputStream fis = null;
    try {
    fis = openFileInput(FILENAME);

    } catch (FileNotFoundException e) {

    e.printStackTrace();
    }
    try {

    byte[] buffer = new byte[1024];
    int length=0;
    while ((length = fis.read(buffer)) != -1) {
    fileContent.append(new String(buffer));
    System.out.println(“buffer appended “+i+”time”);
    i++;
    }
    fis.read(buffer);

    } catch (IOException e) {

    e.printStackTrace();
    }
    try {
    et.setText(fileContent.toString());
    System.out.println(fileContent.toString());
    fis.close();
    } catch (IOException e) {

    e.printStackTrace();
    }
    }
    });

    delete = (Button)findViewById(R.id.button3);

    delete.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    String FILENAME = “hello_file.txt”;
    String string = “”;
    File dir = getFilesDir();
    File file = new File(dir, FILENAME);
    boolean deleted = file.delete(); }
    });

    }
    }

    mail.xml file is like that

Leave a Reply