Android:外部存储上的 mkdirs()/mkdir() 返回 false

发布于 2024-12-01 10:45:49 字数 858 浏览 0 评论 0原文

我对此感到疯狂:

Log.d("STATE", Environment.getExternalStorageState());
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "work_data");
Log.d("PATH", f.getAbsolutePath());
if (!f.exists()) {
    Log.d("MAKE DIR", f.mkdirs() + "");
}

输出日志如下所示:

STATE     mounted
PATH      /mnt/sdcard/DCIM/work_data
MAKE DIR  false

我确保添加了正确的权限:

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

但我不知道为什么它无法创建文件夹。我也一步步使用了mkdir(),但结果是一样的。请帮我。我在谷歌上搜索了很多,并且在这个愚蠢的事情上花费了至少两天的时间。感谢您的帮助!!

编辑:

对不起大家!我在 标记中添加了 。这是我的错误!不过还是谢谢大家的回复。

I'm driven crazy with this:

Log.d("STATE", Environment.getExternalStorageState());
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "work_data");
Log.d("PATH", f.getAbsolutePath());
if (!f.exists()) {
    Log.d("MAKE DIR", f.mkdirs() + "");
}

The output log looks like this:

STATE     mounted
PATH      /mnt/sdcard/DCIM/work_data
MAKE DIR  false

I made sure to add the correct permission:

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

But I don't know why it could not create the folder. I also used mkdir() step by step but the result is the same. Please help me. I have googled so much and spent at least 2 days on this stupid thing. Thanks for your help!!

EDITING:

Sorry everyone! I had added <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in <application> tag. this was my mistake! But thank you all for reply.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

苄①跕圉湢 2024-12-08 10:45:49

我遇到了同样的问题,我确信我已经将权限标签放在了正确的位置,但是 mkdirs 还没有工作,我的系统是 Android 6.0,我现在解决了它,你可以检查如下:

  1. 确保你的 put中的权限标记。
  2. 打开手机中的“设置/应用程序”,检查您的应用程序的权限(我发现我的清单声明中的权限不在这里),像这样打开权限开关。(我发现它默认是关闭的,这使得“mkdirs”失败)

enter图片描述这里

I got the same problem,and I am sure I had put the permission tag in the right place,but mkdirs didn't work yet, my system is Android 6.0, I resolve it now , you can check as below:

  1. make sure your put the permission tag in .
  2. open "setting/application" in your phone,check your application's permission(I found the permission in my manifest statement is not here),open the switch of the permission like this.(I found it is closed in default which make "mkdirs" failed)

enter image description here

浮萍、无处依 2024-12-08 10:45:49

我也遇到了同样的问题,我已经搜索了一周的所有内容试图找到答案。我想我找到了它,而且我认为它非常简单,您必须将使用权限声明放在正确的位置...

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.company.name" 
    android:versionCode="1"
    android:versionName="0.2">

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

当我将它放在中时 ,部分它不起作用。

I have had the same problem and I have searched everything for a week trying to find the answer. I think I found it and I think it's ridiculously easy, you have to put the uses-permission statement in the right place...

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.company.name" 
    android:versionCode="1"
    android:versionName="0.2">

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

When I had it inside the <application></application> section it did not work.

心凉怎暖 2024-12-08 10:45:49

仅当您的 targetSdkVersion 为 29 或更高时才适用

。Environment.getExternalStorageDirectory() 在 API 级别 29 中已弃用。

要获得相同的功能,请使用此行。

File mediaStorageDir = context.getExternalFilesDir(null);

如果您已检查了所有可能的错误,请尝试此修复。

已经在这里回答 - https://stackoverflow.com/a/61480077/7764015

Applicable only if your targetSdkVersion is 29 or above

Environment.getExternalStorageDirectory() is deprecated in API level 29.

To get the same functionality use this line

File mediaStorageDir = context.getExternalFilesDir(null);

If you have checked all the possible errors then try this fix.

Already answered here - https://stackoverflow.com/a/61480077/7764015

伤痕我心 2024-12-08 10:45:49

我知道这是一篇旧文章,但也许​​我的回答可以帮助别人。

经过几天处理这个问题后,我意识到,虽然手机连接到电脑(在开发过程中总是如此),但 SD 卡不可用。因此,在其上创建目录或文件的任何尝试都会失败。
为了使其“更容易”,它的行为似乎根据被测电话的不同而有所不同。

我知道这听起来是一个相当愚蠢的问题,但它花费了很多时间,也许其他人可以节省下来。

I know this is an old post but perhaps my answer can help somebody.

After several days dealing with this problem I have realized that while the phone is connected to the PC, which it turns to be always during development, the SD card is not available. Thus making to fail any attempt to create a directory or file over it.
To make it "easier" it seemed to behave differently depending of the telephone under test.

I know it can sound quite a silly problem, but it cost a lot of time that maybe some other can save.

少女情怀诗 2024-12-08 10:45:49

在OnCreate()中添加这行代码

ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);

add this line of code in OnCreate()

ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
花间憩 2024-12-08 10:45:49

可能现在回答已经太晚了,但是如果您已经允许 R/W 权限(也有运行时权限)并且仍然不起作用,请在您的 AndroidManifest.xml 中添加下面提到的行

<application
........
........
android:requestLegacyExternalStorage="true">

注意:这如果您的目标是 Android 10+,则必须为必填项

Might be it's too late for answer but if you already allowed R/W permission(Runtime Permission too) and still doesn't work add this below mentioned line in your AndroidManifest.xml

<application
........
........
android:requestLegacyExternalStorage="true">

Note: this must required if you'r targeting Android 10+

转瞬即逝 2024-12-08 10:45:49

mkdirs() 仅当目录已创建时才返回 true。如果它已经就位,它应该返回 false。所以我敢打赌这个目录已经存在。

mkdirs() only returns true if the directory was created. If it is in place already, it should return false. So I would bet this directory already exists.

寄居者 2024-12-08 10:45:49
<application
        .....
        android:requestLegacyExternalStorage="true">

工作顺利。

<application
        .....
        android:requestLegacyExternalStorage="true">

work well.

一生独一 2024-12-08 10:45:49

我遇到了同样的问题,我只是想分享我的解决方案。
根据安卓
从 Android 4.4 开始,在应用的私有目录中读取或写入文件不需要 READ_EXTERNAL_STORAGE 或 WRITE_EXTERNAL_STORAGE 权限。

因此,您可以声明仅在较低版本的 Android 上才应请求该权限:添加 maxSdkVersion 属性:

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

但是 maxSdkVersion 是问题所在,我刚刚删除了它,现在它可以工作了。

I had the same issue, and I just wanted to share my fix.
as per android
Beginning with Android 4.4, reading or writing files in your app's private directories does not require the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions.

So you can declare the permission should be requested only on the lower versions of Android by adding the maxSdkVersion attribute:

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

but maxSdkVersion is the issue, I just removed it and now it works.

稳稳的幸福 2024-12-08 10:45:49

把这个

Log.d("MAKE DIR", f.mkdir() + "");

代替

Log.d("MAKE DIR", f.mkdirs() + "");

或尝试这个

String s=Environment.getExternalStorageDirectory().toString()+"/";
File f = new File(s+"DCIM/work_data");

put this

Log.d("MAKE DIR", f.mkdir() + "");

instead of

Log.d("MAKE DIR", f.mkdirs() + "");

or try this

String s=Environment.getExternalStorageDirectory().toString()+"/";
File f = new File(s+"DCIM/work_data");
笑梦风尘 2024-12-08 10:45:49

你的代码对我来说工作得很好。你的代码没有任何问题。
如果您要创建一个目录,请使用 f.mkdir() 而不是 f.mkdirs()
您可以在 mnt => 中看到您的文件夹SD卡=> DCIM=>工作数据

Your code is working fine for me.There is no any thing wrong in your code.
Just if you are making one directory use f.mkdir() instead of f.mkdirs()
You can see your folder in mnt => Sd card => DCIM => work_data

陪我终i 2024-12-08 10:45:49

如果你有android 6.0及以上版本,请确保你的gradle文件中的目标sdk小于22:

targetSdkVersion 22

否则你需要实现运行时权限。

If you have android 6.0 and more, make sure your target sdk in gradle file less than 22:

targetSdkVersion 22

or you need to implement run time permissions.

影子是时光的心 2024-12-08 10:45:49

这可能会对将来的某人有所帮助。

问题也可能是你写了地址“/File/Address/”,而不是你应该写

File.separator + "File" + File.separator + "Address" + File.separator

这是一件小而愚蠢的事情,但在浪费了我几个小时的时间后,这对我有用。

This might help someone in the future.

the problem might also be that you write the address "/File/Address/" instead you should write

File.separator + "File" + File.separator + "Address" + File.separator

This is such a small and stupid thing but this worked for me after wasting hours of my time.

暮光沉寂 2024-12-08 10:45:49

如果您的目标是 Android api 29,则将其添加到您的 AndroidManifest.xml

If you're targeting Android api 29 then add this in your AndroidManifest.xml

<application android:requestLegacyExternalStorage="true">

南渊 2024-12-08 10:45:49

当 mkdirs() 不断返回 false 时,我尝试在外部存储“Test/Test1/Test2”中创建一组子文件夹。事实证明,“Test”是外部存储根目录中文件夹的保留字。这是在 Motorola G (XT1541) 上进行的,也可能适用于其他设备。

I tried to make a set of subfolders in external storage 'Test/Test1/Test2' when mkdirs() kept returning false. Turns out that 'Test' is either a reserved word for a folder in the external storage root. This was on a Motorola G (XT1541) and may apply to other devices as well.

情绪失控 2024-12-08 10:45:49

对于新设备,您必须征求用户许可。

您可以在创建文件之前这样做:

            boolean hasPermission = (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermission) {
            //ask permission
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_STORAGE);
        }
        else {

           //you have permission, create your file
        }

在用户操作之后,您可以处理结果。

  @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case 1: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //you have permission, create your file
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(MainActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}

For new devices, you have to ask user permission.

You can do that like this before create your file:

            boolean hasPermission = (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermission) {
            //ask permission
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_WRITE_STORAGE);
        }
        else {

           //you have permission, create your file
        }

After user's action, you can handle result.

  @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case 1: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //you have permission, create your file
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(MainActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文