Recipe 10.3 Saving Files to the Data Directory

Android versions
Level 1 and above
Source code to download from

If the data you want to preserve cannot be best represented as key/value pairs, then you might want to use the primitive method of saving it directly to the filesystem as files. This option is useful for saving long strings of text, or binary data.


To create a file for saving, you can use the openFileOutput() method, specifying the filename and the mode in which you want the file to be opened. This method will then return a FileOutputStream object:

package net.learn2develop.files;

import android.os.Bundle;

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        //---writing to files---
        try {
            FileOutputStream fOut = 
                openFileOutput("textfile.txt", MODE_PRIVATE);
        } catch (IOException ioe) {


For writing bytes 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:

package net.learn2develop.files; import; import; import; import; import android.os.Bundle; import android.widget.Toast; ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.