在/ sdcard中创建目录失败

时间:2010-10-04 07:51:27

标签: android file directory io

我一直在尝试以编程方式在/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");
}

13 个答案:

答案 0 :(得分:150)

这里要考虑三件事:

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

    Environment.getExternalStorageDirectory();
    
  2. 您必须通过在 AndroidManifest.xml 文件中添加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 
    }
    

答案 1 :(得分:25)

将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
    }
}

更多信息请阅读&#34; Requesting Permissions at Run Time&#34;

答案 2 :(得分:16)

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

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

答案 3 :(得分:15)

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

答案 4 :(得分:7)

如果您使用Android 6并编译目标&gt; = 23,请不要忘记我们现在正在使用runtime permissions。因此,在清单中提供权限已经不够了。

答案 5 :(得分:6)

使用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 :(得分:2)

在android api&gt; = 23

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

而不是

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

答案 7 :(得分:1)

您是否拥有在清单中写入SD卡的权限? 在http://developer.android.com/reference/android/Manifest.permission.html

查找WRITE_EXTERNAL_STORAGE

答案 8 :(得分:1)

是不是已经创建了?如果文件夹已经存在,则Mkdir返回false mkdir

答案 9 :(得分:1)

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

来做到这一点
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;
}

}

答案 10 :(得分:0)

我错误地将两者都包括在内:

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

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

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

答案 11 :(得分:0)

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

答案 12 :(得分:0)

如果错误发生在 Android 6.0 和 API >=23 ;仅在 AndroidManifest.xml 中授予权限还不够。

你必须给运行时权限,你可以在这里参考更多 Runtime Permission

                       (or)

Google 在 Android Q 上有一个新功能:外部存储的过滤视图。一个快速解决方法是在 AndroidManifest.xml 文件中添加此代码:< /p>

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

    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true">
     ...
     ...
    </application>
</manifest>

您可以在此处阅读更多相关信息:https://developer.android.com/training/data-storage/compatibility


内部存储与二级存储

内部存储在API中被称为“外部存储”;不是“二级存储”

Environment.getExternalStorageDirectory();

Environment 文档中所述