Android: how to write a file to internal storage

no file is written neither on the phone or on the emulator.

Yes, there is. It is written to what the Android SDK refers to as internal storage. This is not what you as a user consider to be "internal storage", and you as a user cannot see what is in internal storage on a device (unless it is rooted).

If you want to write a file to where users can see it, use external storage.

This sort of basic Android development topic is covered in any decent book on Android app development.


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.