Android write to file (internal storage)
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:
The second parameter to
The file is saved in
- Open the file with
Context.openFileOutput, which returnsjava.io.FileOutputStream. - Write to the file.
- 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.