在/sdcard 中创建目录失败 [英] Creating a directory in /sdcard fails

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

问题描述

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

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

推荐答案

这里需要考虑三件事:

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

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

  • 您必须通过在 AndroidManifest.xml 文件中添加一个使用权限条目来通知 Android 您的应用程序需要写入外部存储:

  • 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"/>
    

  • 如果这个目录已经存在,那么 mkdir 将返回 false.所以检查该目录是否存在,如果不存在则尝试创建它.在您的组件中,使用以下内容:

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

  • 这篇关于在/sdcard 中创建目录失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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