Writing Files To Disk

2012-03-18 by

If you are used to the Microsoft System.IO namespace, you will probably find that the java.io namespace is not far off. While you may be used to some of the shortcuts offered by Microsoft, the java implementation is not too hard to follow. The following steps show how to write a file to disk on the android in a static location. The next tip will show you how to read the same file from disk. This process is very helpful when trying to save data for application settings or long term data files. Using custom serialization methods you can easily and quickly write your code objects out to disk and read them back in.

You want to ensure that you add the imports below to the header of your java file for ease of coding.

import java.io.FileOutputStream;

import java.io.IOException;

With Android, you need to also have a Context object to open the file. I always add the following import as well

import android.content.Context;

Now we create a method that takes in a Context object and a string as a parameter saves the file to disk.

private void writeToDisk(Context _context, String data) throws IOException

{

FileOutputStream fOut = null;

fOut = _context.openFileOutput("Temp.txt", Context.MODE_WORLD_READABLE);

OutputStreamWriter osw = new OutputStreamWriter(fOut);

// Write the string to the file

osw.write(data);

osw.flush();

osw.close();

}

This is how you save a file to disk. The next lesson will be about how to then read this file from disk quickly and easily. In later posts I will also go into XML Serialization, WCF, Web Client, and other UI topics.