IT-Swarm.Net

在/ sdcard中创建目录失败

我一直在尝试以编程方式在/sdcard中创建一个目录,但它无法正常工作。下面的代码总是输出directory not created.

boolean success = (new File("/sdcard/map")).mkdir(); 
if (!success) {
    Log.i("directory not created", "directory not created");
} else {
    Log.i("directory created", "directory created");
}
54
sajjoo

这里有三件事需要考虑:

  1. 不要假设SD卡安装在/sdcard(在默认情况下可能是真的,但最好不要硬编码。)。您可以通过查询系统获取SD卡的位置:

    Environment.getExternalStorageDirectory();
    
  2. 您必须通过在 AndroidManifest.xml file中添加uses-permission条目来通知Android您的应用程序需要写入外部存储:

    <uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  3. 如果此目录已存在,则mkdir将返回false。因此,请检查目录是否存在,然后尝试创建目录(如果该目录不存在)。在您的组件中,使用以下内容:

    File folder = new File(Environment.getExternalStorageDirectory() + "/map");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdir();
    }
    if (success) {
        // Do something on success
    } else {
        // Do something else on failure 
    }
    
150
Gopinath

快速,可靠且价格合理的云托管

注册并在30天内获得$50奖金!

将Android手机更新为6.0(API级别23)后,我遇到了同样的问题。以下解决方案适用于我。希望它也能帮到你。.

请检查您的Android版本。如果> = 6.0(API级别23),则不仅需要包括

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

在您的AndroidManifest.xml中,还有 在调用mkdir() 之前请求权限。代码snopshot。.

public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
public int mkFolder(String folderName){ // make a folder under Environment.DIRECTORY_DCIM
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)){
        Log.d("myAppName", "Error: external storage is unavailable");
        return 0;
    }
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        Log.d("myAppName", "Error: external storage is read only.");
        return 0;
    }
    Log.d("myAppName", "External storage is not read only or unavailable");

    if (ContextCompat.checkSelfPermission(this, // request permission when it is not granted. 
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Log.d("myAppName", "permission:WRITE_EXTERNAL_STORAGE: NOT granted!");
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

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

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),folderName);
    int result = 0;
    if (folder.exists()) {
        Log.d("myAppName","folder exist:"+folder.toString());
        result = 2; // folder exist
    }else{
        try {
            if (folder.mkdir()) {
                Log.d("myAppName", "folder created:" + folder.toString());
                result = 1; // folder created
            } else {
                Log.d("myAppName", "creat folder fails:" + folder.toString());
                result = 0; // creat folder fails
            }
        }catch (Exception ecp){
            ecp.printStackTrace();
        }
    }
    return result;
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

更多信息请阅读“ 在运行时请求权限

25
Diiiiii

SD卡的正确路径是

/mnt/sdcard/

但是,如前所述,你不应该硬编码。如果您使用的是Android 2.1或之后,请使用

getExternalFilesDir(String type) 

除此以外:

Environment.getExternalStorageDirectory()

仔细阅读 https://developer.Android.com/guide/topics/data/data-storage.html#filesExternal

此外,您还需要使用此方法或类似的方法

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

然后检查您是否可以访问SD卡。如上所述,阅读官方文档。.

另一种选择,也许你需要使用 mkdirs 而不是 mkdir

file.mkdirs()

创建由此文件的尾随文件名命名的目录,包括创建此目录所需的完整目录路径。

16
Maragues

重启 您的Android设备。重新启动设备后,事情开始对我有用。.

15
Uriel Frankel

如果您使用Android 6并编译目标> = 23,请不要忘记我们现在正在使用 运行时权限 。因此,在清单中提供权限已经不够了。.

7
Kuno

使用mkdirs()而不是mkdir()..它对我有用:)

File folder = new File(Environment.getExternalStorageDirectory()+"/Saved CGPA");
if(!folder.exists()){
    if(folder.mkdirs())
    Toast.makeText(this, "New Folder Created", Toast.LENGTH_SHORT).show();
}

File sdCardFile = new File(Environment.getExternalStorageDirectory()+"/Saved CGPA/cgpa.html");
6
Bala Vishnu

在Android api> = 23

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

代替

    <app:uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"/>
2
Vahe Gharibyan
1
Matthieu

它已经创建了吗?如果文件夹已经存在,Mkdir返回false mkdir

1
fedj

有很多事情你需要担心1.如果你使用的是Android Bellow Marshmallow,那么你必须在Manifest File中设置permesions。 2.如果您正在使用更高版本的Android版本意味着从Marshmallow到Oreo现在您必须转到应用程序信息并手动设置存储的App权限。如果你想在运行时设置它,你可以通过下面的代码来做到这一点

public  boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(Android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}

}

1
Nadeem Bhat

我犯了包括两个错误的错误:

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

和:

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

按上述顺序。所以当我拿出第二个许可(READ)时,问题就消失了。.

0
user2638345
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/FoderName");
if (!f.exists()) {
    f.mkdirs();
}
0
ashvin sapariya