Android: how to write a file to internal storage

Use the below code to write a file to internal storage:

public void writeFileOnInternalStorage(Context mcoContext, String sFileName, String sBody){      
    File dir = new File(mcoContext.getFilesDir(), "mydir");
    if(!dir.exists()){
        dir.mkdir();
    }

    try {
        File gpxfile = new File(dir, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (Exception e){
        e.printStackTrace();
    }
}

Starting in API 19, you must ask for permission to write to storage.

You can add read and write permissions by adding the following code to AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

You can prompt the user for read/write permissions using:

requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);

and then you can handle the result of the permission request in onRequestPermissionsResult() inside activity called from it.

Leave a Comment