无法从外部存储读取或创建文件,即使已经授予了读写权限。

huangapple go评论118阅读模式
英文:

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

问题

这是清单文件:

<?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>

我使用了 TedPermission。
以日期命名的文本文件(例如:2020_10_23.txt)
从外部存储(例如:storage/emulated/0/myDiary/2020_10_23.txt)
进行输入/输出操作。

这是 MainActivity 中的核心代码:

PermissionListener permissionlistener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {
            Toast.makeText(MainActivity.this, "已授予权限", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPermissionDenied(List<String> deniedPermissions) {
            Toast.makeText(MainActivity.this, "权限被拒绝\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("外部存储读取/写入被拒绝")
                .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 方法不允许路径分隔符。                    
                    File current_file = new File(myDir + "/" + fileName);

                    if (!current_file.getParentFile().exists()) {
                        if (!current_file.getParentFile().mkdirs()) {
                            Toast.makeText(getApplicationContext(),
                                    "无法创建文件夹:" + myDir, Toast.LENGTH_SHORT).show();
                        }
                    }

                    if (!current_file.exists()) {
                        if (!current_file.createNewFile()) {
                            Toast.makeText(getApplicationContext(),
                                    "无法创建文件:" + 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 + " 已保存", Toast.LENGTH_SHORT).show();

                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),
                            "无法保存文件:" + myDir + "/" + fileName, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }

            }
        });

...

// 从外部存储读取文本文件
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("修改");
        } catch (IOException e) {
            edtDiary.setHint("没有现有日记");
            btnWrite.setText("新建保存");
        }
        return diaryStr;
    }

Android 版本:11

应用程序权限:

无法从外部存储读取或创建文件,即使已经授予了读写权限。

这是日志输出:

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)
...

无法在 storage/emulated/0 上创建文件夹 'myDiary'。
**我已经尝试了我能想到的一切。为什么无法创建文件夹或文件,即使我已经授予了外部存储的 I/O 权限?**

注意:由于您要求不翻译代码部分,我已经保留了原始代码,只翻译了注释和字符串文字。

英文:

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?

答案1

得分: 0

使用以下代码

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();
    }
}

在活动中

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();
        }
    };
英文:

Use this

public class Folder
{
private final File appDataFolder;
public Folder()
{
File file = Environment.getExternalStorageDirectory();
appDataFolder = new File(file, &quot;AppDataFolder&quot;);
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(&quot;myDiary&quot;);
Toast.makeText(MainActivity.this, &quot;Permission granted&quot;, Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionDenied(List&lt;String&gt; deniedPermissions) {
Toast.makeText(MainActivity.this, &quot;Permission denied\n&quot; + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};

答案2

得分: 0

在Android 11上,您无法访问外部存储的根目录。
您无法在/storage/emulated/0中创建文件或文件夹。
但是... 您可以写入/storage/emulated/0上的通常公共文件夹,比如
下载(Download)、文档(Documents)、相机(DCIM)、图片(Pictures)、闹钟(Alarms)等等。
查看一下您的设备上已经有哪些文件夹,您可以在很大程度上将它们用于读取和/或写入操作。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月23日 14:45:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64495159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定