Android Internal Storage :

In Android you can also save files (text file etc) directly on the device’s internal storage. By default,Saving and Loading Files to the internal storage are private to your application and different applications will not access them (nor can the user). once the user uninstalls this application, these files will automatically remove.

android read and write text file example

In Android data storage, It’s good practice to use Shared Preferences or a database to store your application data, but there are still times once you’ll need to use files directly rather than rely on Android’s managed mechanisms.

Sometime want to save data which have not be best represented as key/value pairs, then you may need to use the primitive method of saving it on to the filesystem as files. Saving data in text file is helpful for saving long strings of text, or binary data etc in your application.

Solution Steps Write and Read Text File :

As well as the standard Java I/O classes and methods, android also offers openFileInput and openFileOuput to modify reading and writing streams from and to local files. In  android to create a file and saving, you can use the openFileOutput() method and openFileInput() method to open a file for reading:

1. Add Following xml code into activity_main.xml

File : res/layout/activity_main.xml

2. Open “MainActivity.java” file and add following JAVA code.

File : src/package-name/MainActivity.java

For writing text to a file, use the OutputStreamWriter class and use its write() method to write a string to the file. To save the changes to the file, use its close() method:

 

Output of  Android Read Write Text File in emulator :

android read and write text file example

Note : This example (Project) is developed in Eclipse Version Kepler,tested on Android 4.4.2 (KitKat Version) and SDK build-tools 23.0

Download Android Custom Read Write Text File Source code :


  1. Where do we put the following code??

    String MY_FILE_NAME = “mytextfile.txt”;
    // Create a new output file stream
    FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
    // Create a new file input stream.
    FileInputStream fileis = openFileInput(My_FILE_NAME);

  2. How do you display only a section of data from a text file in a text view. For example if you have a text file with 100 paragraphs and you only want to display one middle paragraph?

Leave a Reply