0

I am trying to access a file in Android, below is the code:

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"sos/xconfig.txt");

if(!file.exists())
   return text.toString();

 BufferedReader br = new BufferedReader(new FileReader(file));
 String line;

 while ((line = br.readLine()) != null) {
      text.append(line);
      text.append('\n');
    }
 br.close();

I am also checking for read and write permission like this before reading :

 if (ContextCompat.checkSelfPermission(activity, permission)
            == PackageManager.PERMISSION_DENIED) {

        // Requesting the permission
        ActivityCompat.requestPermissions(activity,
                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
                requestCode);
        return false;
    }
    else {
        return true;
    }

But I am still getting an error at this line : new FileReader(file).

Error : java.io.FileNotFoundException: /storage/emulated/0/sos/xconfig.txt: open failed: EACCES (Permission denied)

NOTE: I have already added uses-permission in menifest file.

<uses-permission
    android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Piyush Chandra
  • 109
  • 3
  • 14

1 Answers1

1

Are u using Android Q ? If that is the case you need to add this attribute in your AndroidManifest file :

<manifest ... >
    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true" ... >
     ...
    </application>
</manifest>

Source : Exception 'open failed: EACCES (Permission denied)' on Android

Kévin Giacomino
  • 487
  • 4
  • 11