Android write to file (internal storage) 

Joined:
07/27/2010
Posts:
130

April 15, 2011 09:00:54    Last update: April 15, 2011 09:00:54
Sample code for writing to a file in the internal storage. There are three steps:
  1. Open the file with Context.openFileOutput, which returns java.io.FileOutputStream.
  2. Write to the file.
  3. Close the file.


import java.io.*;
import android.content.Context;
.
.
.
public void writeFile() {
	try {
	    InputStream in = getResources().openRawResource(R.xml.books);
	    byte[] buffer = new byte[4096];
	    OutputStream out = openFileOutput("xml.bin", Context.MODE_PRIVATE);
	    int n = in.read(buffer, 0, buffer.length);
	    while (n >= 0) {
		out.write(buffer, 0, n);
		n = in.read(buffer, 0, buffer.length);
	    }
	    in.close();
	    out.close();
	}
	catch (IOException e) {
	    Log.d(LOG_TAG, e + "");
	}
}

The second parameter to openFileOutput is the operating mode. Available values are:
  • Context.MODE_PRIVATE
  • Context.MODE_APPEND
  • Context.MODE_WORLD_READABLE
  • Context.MODE_WORLD_WRITEABLE


The file is saved in /data/data/<package_name>/files.
Share |
| Comment  | Tags