How to create a file on Android Internal Storage?

Buda Gavril picture Buda Gavril · Feb 16, 2011 · Viewed 135.7k times · Source

I want to save a file on internal storage into a specific folder. My code is:

File mediaDir = new File("media");
if (!mediaDir.exists()){
   mediaDir.createNewFile();
   mediaDir.mkdir();

}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();

getLocalPath returns /data/data/myPackage/files/media/qmhUZU.jpg but when I want to create the media folder I'm getting the exception "java.io.IOException: Read-only file system". Any ideas how to write my files on internal phone storage in in folder media? Thanks.

Answer

Audrius picture Audrius · Feb 16, 2011

You should use ContextWrapper like this:

ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);

As always, refer to documentation, ContextWrapper has a lot to offer.