Can't write text files to documents folder in Android

Issue

I have an app that I am trying to write values from my camera to a text file.

Yesterday, I was able to solve this issue: How to write and constantly update a text file in Android, although after re-installing I am no longer able to write files to documents directory.

I am getting the following exception:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Documents/1658486312697.txt: open failed: EPERM (Operation not permitted)

Writting code:

long time = System.currentTimeMillis();
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
try {
    File outFile1 = new File(path+"/"+String.valueOf(time)+".txt");
    Log.e("outFile1:", outFile1.getAbsolutePath());
    Writer out = new BufferedWriter(new OutputStreamWriter(
                                 new FileOutputStream(outFile1,true), "utf-8"), 10240);
    for (int i = 10; i < 110602; i++) {
        out.write(values[i] + "\r\n");
    }
    out.flush();
    out.close();
} catch (Exception e){
    e.printStackTrace();
}

Permissions on AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

I am currently testing on Android 12 device
I’d like to know why can I not save my text files to documents and what needs to be done to save it the right way.

Solution

It’s because outFile1 doesn’t exist.

File outFile1 = new File(path+"/"+String.valueOf(time)+".txt");
outFile1.createNewFile(); //add this line

And make sure you have allowed MANAGE_EXTERNAL_STORAGE permission in Application Setting. read more here

And also for below android 11 devices you have to ask for WRITE_EXTERNAL_STORAGE permission using "Permission Dialog". read more here

Answered By – Bhavesh Rangani

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published