Unable to create file on Android external drive

I want to create a .txt file and save it to the external storage of an Android phone. I added permission to my Android manifest. When I run the code, it does not give me any error, but the file is never created. Not sure what I'm 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); } } 
+4
source share
3 answers
 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(); } 
+8
source

you need the appropriate permission:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
+13
source

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

 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); } } 
0
source

Source: https://habr.com/ru/post/1344554/


All Articles