创建一个目录中/ SD卡出现故障 [英] Creating a directory in /sdcard fails

查看:147
本文介绍了创建一个目录中/ SD卡出现故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图以编程方式创建的 / SD卡的目录中,但它不工作。下面总​​是code输出目录中没有创建。

 布尔成功=(新的文件(/ SD卡/图))的mkdir();
如果(!成功){
    Log.i(目录没有创建,没有创建目录);
} 其他 {
    Log.i(目录下创建,目录下创建);
}
 

解决方案

有三件事情要考虑这里:

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

      Environment.getExternalStorageDirectory();
     

  2. 您有您的应用程序需要写入外部存储通知Android的加入在 AndroidManifest.xml中文件的用途,权限项:

     <使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/>
     

  3. 如果这个目录已经存在,那么MKDIR会返回false。因此,检查的目录是否存在,然后尝试创建它,如果它不存在。 在您的组件,使用这样的:

     文件夹=新的文件(Environment.getExternalStorageDirectory()+/图);
    布尔成功= TRUE;
    如果(!folder.exists()){
        成功= folder.mkdir();
    }
    如果(成功){
        //做一些事情上的成功
    } 其他 {
        //做别的事情上失败
    }
     

I have been trying to create a directory in /sdcard programmatically, but it's not working. The code below always outputs 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");
}

解决方案

There are three things to consider here:

  1. Don't assume that the sd card is mounted at /sdcard (May be true in the default case, but better not to hard code.). You can get the location of sdcard by querying the system:

    Environment.getExternalStorageDirectory();
    

  2. You have to inform Android that your application needs to write to external storage by adding a uses-permission entry in the AndroidManifest.xml file:

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

  3. If this directory already exists, then mkdir is going to return false. So check for the existence of the directory, and then try creating it if it does not exist. In your component, use something like:

    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 
    }
    

这篇关于创建一个目录中/ SD卡出现故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆