Android Save Data To File
Post
Cancel

Save Data To File

Storing application data is one of the most important part in Android development. And the easiest way to do that is saving data to a file.

In this post, I will show you how to save and read data to/ from a file in Android.

A - Save data to file

  1. First of all, call theĀ FileOutputStream openFileOutput(String name, int mode) method to create a FileOutputStream object. This object will take responsibility to write data to a file.
  • name: The name of file
  • mode: Writting mode
    • MODE_PRIVATE : That file onlyĀ Ā can be accessed by the application which created it
    • MODE_WORLD_READALBE : That file can be read by any application
    • MODE_WORLD_WRITEABLE : That file can be read and written by any application
  1. To write data file, call theĀ FileOutputStream.write() method.

  2. After you saving all data to file, callĀ FileOutputStream.close() method to close the output stream and finish the task.

B - Read data from file

Reading data from a file is very similar to writing data.

  1. First, call theĀ FileInputStream openFileInput(String name) method to create aĀ FileInputStream object. This one will handle all tasks that related to reading data from a file.
  • name: The file name you want to read data from
  1. Call theĀ FileInputStream.read() method to read all data from that file.

  2. Finally, call theĀ FileInputStream.close() method to close the input stream after the reading task completed.

Below is the demo application for this post:

When user hit the Save button, the application will save the text in EditText to file in device.

And when the Load button was hit, it will load all data from file to TextView on the screen.

C - Download source code

http://www.mediafire.com/?mb6amzm2kta8s4w

This post is licensed under CC BY 4.0 by the author.