Home > Net >  Read an xlsx file from /Documents/: EACCES (Permission denied)
Read an xlsx file from /Documents/: EACCES (Permission denied)

Time:01-08

My app has to read an xlsx file from /Documents/. I copied an Excel file (text.xlsx) from PC to the internal storage of the phone: /storage/emulated/0/Documents/test.xlsx.

The code is:

    public void loadExcel(View view) {
        verifyStoragePermissions(Settings.this);

        String excelFile =  Environment.getExternalStorageDirectory()   "/Documents/text.xlsx" ;
        File file = new File(excelFile);
        Log.d("XXXXX", "excelFile = "   excelFile);
        if (file.exists()) {
            Log.d("XXXXX","The file exists");
        } else {
            Log.d("XXXXX","The file doesn't exist");
        }

        try {
            FileInputStream inputStream = new FileInputStream(excelFile);
            try {
                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Log.e("XXXXX", "File for found: "   e.getMessage());
            e.printStackTrace();
        }
    }

The log is:

2023-01-07 01:20:05.223 17589-17589/it.linuxp.psswordlist D/XXXXX: excelFile = /storage/emulated/0/Documents/text.xlsx
2023-01-07 01:20:05.224 17589-17589/it.linuxp.psswordlist D/XXXXX: The file exists
2023-01-07 01:20:05.230 17589-17589/it.linuxp.psswordlist E/XXXXX: File for found: /storage/emulated/0/Documents/text.xlsx: open failed: EACCES (Permission denied)

In Android Manifest I wrote the permissions:

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

The routine

verifyStoragePermissions(Settings.this);

is taken from Exception 'open failed: EACCES (Permission denied)' on Android

So, I cannot understand where is the problem. Please, help me. Thank you.

--------------------

CodePudding user response:

You do not have access to content in Documents/ on Android 11 , unless your app was the one that put the content there in the first place.

Use ACTION_OPEN_DOCUMENT / ActivityResultContracts.OpenDocument and allow the user to choose the document to open. Use ContentResolver and openInputStream() to get an InputStream on that content, using the Uri that you get from ACTION_OPEN_DOCUMENT / ActivityResultContracts.OpenDocument. Try using that InputStream with your new XSSFWorkbook() call.

  • Related