简体   繁体   中英

Impossible to create file on external storage 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);
    }
}

你需要一个适当的权限:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {

     FileOutputStream os = new FileOutputStream(file, true); 
     OutputStreamWriter out = new OutputStreamWriter(os);
         out.write(data);
     out.close();
}

I was able to create the file on the external storage by using the code below:

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 = new FileOutputStream(file); 
        OutputStreamWriter out = new OutputStreamWriter(os);

        out.write(data);
        out.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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM