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.

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.

Save to Internal storage

data="my Info to save";

try {

    FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
    fOut.write(data.getBytes());
    fOut.close();   

    Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Read from Internal storage

try {

    FileInputStream fin = openFileInput(file);
    int c;
    String temp="";

    while( (c = fin.read()) != -1){
        temp = temp + Character.toString((char)c);
    }
    tv.setText(temp);
    Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}