Recipe 10.3 Saving Files to the Data Directory

Android versions
Level 1 and above
Permissions
None
Source code to download from Wrox.com
Files.zip

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.

Solution

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 java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //---writing to files---
        try {
            FileOutputStream fOut = 
                openFileOutput("textfile.txt", MODE_PRIVATE);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

}        

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 java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import android.app.Activity; 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.