Search code examples
androidfilesystemsandroid-permissionsandroid-11

can not FileWriter on anroid 11


I used a code to write to the system root , Ever since Android 11 was released this code can not write my file on device and displays this error

java.io.FileNotFoundException: /storage/emulated/0/Android/Data/systemInfo: open failed: EACCES (Permission denied)

My code works on Android 10 devices and below

this is my code :

 private void generateNoteOnRoot(String fileName,String sBody) {
    try {
        File systemFile = new File(Environment.getExternalStorageDirectory(), "Android/Data");
        if (!systemFile.exists())
        {
            systemFile.mkdirs();
        }
        File info = new File(systemFile, fileName);
        FileWriter writer = new FileWriter(info);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("Authentication", "generateNoteOnRoot: "+e.getMessage());
    }
}

Before doing this process , i get the necessary access

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

Solution

  • Try with the following code.

    //Add below permission in manifest.xml and also don't forget to ask file write run time permission.
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    
    //Add below attribute in manifest application tag
    android:requestLegacyExternalStorage="true"
    
    
    //Write below code for file creation
    private fun writeFile(fileData: String, fileName: String) {
    val dir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                .toString() + "/" + "test"
        )
    } else {
        File(
            Environment.getExternalStorageDirectory()
                .toString() + "/${Environment.DIRECTORY_DOCUMENTS}/" + "test"
        )
    }
    dir.apply {
        if (!this.exists()) this.mkdir()
        File(this, "$fileName.txt").apply {
            if (!this.exists()) this.createNewFile()
            FileOutputStream(this).apply {
                write(fileData.toByteArray())
                close()
            }
        }
    }
    }