Home > front end >  Can't write text files to documents folder in Android
Can't write text files to documents folder in Android

Time:07-22

I have an app that I am trying to write temperature values from my thermal 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 < 384*288 10; i  ) {
        out.write(temperature1[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.

CodePudding user response:

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

  • Related