为了账号安全,请及时绑定邮箱和手机立即绑定

在/ sdcard中创建目录失败

/ 猿问

在/ sdcard中创建目录失败

一只名叫tom的猫 2019-12-26 09:30:44

我一直在尝试以/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");

}


查看完整描述

3 回答

?
喵喔喔

这里有三件事要考虑:


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


Environment.getExternalStorageDirectory();

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


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

如果此目录已经存在,则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 

}


查看完整回答
反对 回复 2019-12-26
?
慕田峪7331174

将Android手机更新为6.0(API级别23)后,我遇到了同样的问题。以下解决方案对我有效。希望它也对您有帮助。


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


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

在您的AndroidManifest.xml中,但还需要在调用mkdir()之前请求权限。代码快照。


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

    }

}


查看完整回答
反对 回复 2019-12-26
?
SMILET

sdcard的正确路径是


/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;

}

然后检查是否可以访问sdcard。如前所述,请阅读官方文档。


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


file.mkdirs()

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


查看完整回答
反对 回复 2019-12-26

添加回答

回复

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信