Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impossible to create file on external storage Android

Tags:

java

android

I want to create a .txt file and store it on the external storage of the Android phone. I added the permission to my Android Manifest. When I run the code it doesn't give me any error but the file is never created. Not sure what I am doing wrong.

public void createExternalStoragePrivateFile(String data) {
    // Create a path where we will place our private file on external
    // storage.
    File file = new File(myContext.getExternalFilesDir(null), "state.txt");

    try {

        FileOutputStream os = null; 
        OutputStreamWriter out = null;
        os = myContext.openFileOutput(data, Context.MODE_PRIVATE);
        out = new OutputStreamWriter(os);
        out.write(data);
        os.close();

        if(hasExternalStoragePrivateFile()) {
            Log.w("ExternalStorageFileCreation", "File Created");
        } else {
            Log.w("ExternalStorageFileCreation", "File Not Created");
        }

    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}
like image 652
nyalex5000 Avatar asked Nov 30 '22 17:11

nyalex5000


1 Answers

you need an appropriate permission:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
like image 169
Vladimir Ivanov Avatar answered Dec 05 '22 02:12

Vladimir Ivanov