Search code examples
androidcsvandroid-11

Creating a CSV file in Android 11 Return Error "java.io.FileNotFoundException: EPERM (Operation not permitted)"


Hello I am trying to create a csv file in my android application. My code works when I try to run it on android 10 below. But I cant seem to find a problem why I cant do it on devices that are Android 11 already.

Here is my Manifest Permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<application
        ...
        android:requestLegacyExternalStorage="true">

Here is my code where I create a folder inside the download folder

@NonNull
public static File getStorageDirectory() {
    if (Environment.getExternalStorageState() == null) {

        File f = new File(Environment.getDataDirectory().getAbsolutePath() + "/Download/(Project Name)/");

        if(!f.exists())
            f.mkdirs();
        return f;
    } else {
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/(Project Name)/");
        if(!f.exists())
            f.mkdirs();
        return f;
    }
}

Here is my code on how I create my csv file

File baseDir = Utility.getStorageDirectory();
String fileName = pollutant.getStationName();
String date = Utility.convertDate(new Date().getTime(), "dd-MM-yyyy HH:mm:ss");
File csvFile = new File(baseDir, fileName + "(1hr - "+pollutant.getPollutantName()+")(" + date + ").csv");

FileWriter writer;
if(csvFile.exists() && !csvFile.isDirectory()) {
    writer = new FileWriter(csvFile , true);
} else {
    writer = new FileWriter(csvFile);
}

I am already creating a folder in the download folder in android 11 problem is when I am trying to do the create csv part program return a

java.io.FileNotFoundException: ... open failed: EPERM (Operation not permitted)

I am really having a hard time to fix my problem for devices with android 11


Solution

  • "dd-MM-yyyy HH:mm:ss"

    You have a forbidden character in your file name.

    A : is not allowed.

    Change to "dd-MM-yyyy HH.mm.ss" or so.