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

前端 未结 30 1627
[愿得一人]
[愿得一人] 2020-11-22 00:59

I am getting

open failed: EACCES (Permission denied)

on the line OutputStream myOutput = new FileOutputStream

30条回答
  •  故里飘歌
    2020-11-22 01:30

    In my case I was using a file picker library which returned the path to external storage but it started from /root/. And even with the WRITE_EXTERNAL_STORAGE permission granted at runtime I still got error EACCES (Permission denied).
    So use Environment.getExternalStorageDirectory() to get the correct path to external storage.

    Example:
    Cannot write: /root/storage/emulated/0/newfile.txt
    Can write: /storage/emulated/0/newfile.txt

    boolean externalStorageWritable = isExternalStorageWritable();
    File file = new File(filePath);
    boolean canWrite = file.canWrite();
    boolean isFile = file.isFile();
    long usableSpace = file.getUsableSpace();
    
    Log.d(TAG, "externalStorageWritable: " + externalStorageWritable);
    Log.d(TAG, "filePath: " + filePath);
    Log.d(TAG, "canWrite: " + canWrite);
    Log.d(TAG, "isFile: " + isFile);
    Log.d(TAG, "usableSpace: " + usableSpace);
    
    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }
    

    Output 1:

    externalStorageWritable: true
    filePath: /root/storage/emulated/0/newfile.txt
    isFile: false
    usableSpace: 0
    

    Output 2:

    externalStorageWritable: true
    filePath: /storage/emulated/0/newfile.txt
    isFile: true
    usableSpace: 1331007488
    

提交回复
热议问题