简体   繁体   中英

Failure to read or create a file from external storage even though given read/write permissions

this is manifest file :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

...

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

    <application
        android:requestLegacyExternalStorage="true"
        android:allowBackup="true"

...

</manifest>

i used tedpermission. Text file named by date (ex:2020_10_23.txt) from external storage(ex:storage/emulated/0/myDiary/2020_10_23.txt) for i/o operation.

here core code in mainactivity :

 PermissionListener permissionlistener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {
            Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPermissionDenied(List<String> deniedPermissions) {
            Toast.makeText(MainActivity.this, "Permission denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        TedPermission.with(this)
                .setPermissionListener(permissionlistener)
                .setDeniedMessage("External Storage READ/WRITE Denied")
                .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .check();

...

   final String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
   final File myDir = new File(sdPath + "/myDiary");
   string fileName = Integer.toString(year) + "_"
                        + Integer.toString(monthOfYear + 1) + "_"
                        + Integer.toString(dayOfMonth) + ".txt";

...

 btnWrite.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            public void onClick(View v) {
                try {
                    //openFileoutput Methods does not allow path delimiters.                    
                    File current_file = new File(myDir + "/" + fileName);

                    if (!current_file.getParentFile().exists()) {
                        if (!current_file.getParentFile().mkdirs()) {
                            Toast.makeText(getApplicationContext(),
                                    "Failed to create folder : " + myDir, Toast.LENGTH_SHORT).show();
                        }
                    }

                    if (!current_file.exists()) {
                        if (!current_file.createNewFile()) {
                            Toast.makeText(getApplicationContext(),
                                    "Failed to create file : " + myDir + "/" + fileName, Toast.LENGTH_SHORT).show();
                        }
                    }

                    FileOutputStream outFs = new FileOutputStream(new File(String.valueOf(current_file)));

                    String str = edtDiary.getText().toString();
                    outFs.write(str.getBytes());
                    outFs.close();

                    Toast.makeText(getApplicationContext(),
                            fileName + " is saved", Toast.LENGTH_SHORT).show();

                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),
                            "Failed to save file : " + myDir + "/" + fileName, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }

            }
        });

...
//read text file from external storage
String readDiary(String fName) {
        String diaryStr = null;
        FileInputStream inFs;
        try {
            inFs = new FileInputStream(new File(fName));
            byte[] txt = new byte[500];
            inFs.read(txt);
            inFs.close();
            diaryStr = (new String(txt)).trim();
            btnWrite.setText("modify");
        } catch (IOException e) {
            edtDiary.setHint("no existing diary");
            btnWrite.setText("new save");
        }
        return diaryStr;
    }



Android version: 11

App permissions :

在此处输入图片说明

and this is logcat:

2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err: java.io.IOException: No such file or directory
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err:     at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err:     at java.io.File.createNewFile(File.java:1008)
2020-10-23 15:40:00.986 6178-6178/com.cookandroid.project8_1 W/System.err:     at com.cookandroid.project8_1.MainActivity$3.onClick(MainActivity.java:102)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.view.View.performClick(View.java:7448)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.view.View.performClickInternal(View.java:7425)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.view.View.access$3600(View.java:810)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.view.View$PerformClick.run(View.java:28305)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.os.Handler.handleCallback(Handler.java:938)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.os.Looper.loop(Looper.java:223)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7656)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
2020-10-23 15:40:00.987 6178-6178/com.cookandroid.project8_1 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

it cannot create folder 'myDiary' on storage/emulated/0 I tried everything I could. why cannot create folder,file even i given external storage I/O Permissions?

Use this

public class Folder
{
    private final File appDataFolder;

    public Folder()
    {
        File file = Environment.getExternalStorageDirectory();

        appDataFolder = new File(file, "AppDataFolder");

        if (!appDataFolder.exists()) appDataFolder.mkdir();
    }

    public String getMainFolder()
    {
        return appDataFolder.getAbsolutePath();
    }

    public void deleteMainFolder()
    {
        if (appDataFolder.isDirectory())
        {
            String[] children = appDataFolder.list();

            for (String child : children)
            {
                new File(appDataFolder, child).delete();
            }
        }

        new Folder();
    }

    public void createNewFolder(String folderName)
    {
        File file = new File(appDataFolder, folderName);

        if (!file.exists()) file.mkdir();
    }

    public void createChildFolder(String parentName, String childName)
    {
        String path = appDataFolder.getAbsolutePath() + File.separator + parentName;

        File parent = new File(path);

        File file = new File(parent, childName);

        if (!file.exists()) file.mkdir();
    }
}

and in activity

PermissionListener permissionlistener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {
            new Folder().createNewFolder("myDiary");
            Toast.makeText(MainActivity.this, "Permission granted", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPermissionDenied(List<String> deniedPermissions) {
            Toast.makeText(MainActivity.this, "Permission denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
        }
    };

On Android 11 you have no access to the root of external storage.

You cannot create files or folders in /storage/emulated/0.

But.. you can write to the usual public folders on /storage/emulated/0 like

Download, Documents, DCIM, Pictures, Alarms, a.s.o.

Look which folders there are already on your device and you can mostly use them for read and or write operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM