在/ SD卡中创build一个目录失败

我一直在尝试以编程方式在/sdcard创build一个目录,但它不工作。 下面的代码总是输出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 (在默认情况下可能是true,但最好不要硬编码)。 你可以通过查询系统来获得SD卡的位置:

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

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
  3. 如果这个目录已经存在,那么mkdir将返回false。 所以检查目录的存在,然后尝试创build它,如果它不存在。 在你的组件中,使用类似于:

     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 } 

我更新我的Android手机到6.0(API级别23)后,我有同样的问题。 以下解决scheme对我有用。 希望它可以帮助你。

请检查您的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 } } 

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

SD卡的正确path是

 /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卡。 如上所述,阅读官方文档。

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

 file.mkdirs() 

创build由该文件尾部文件名命名的目录,包括创build该目录所需的完整目录path。

重新启动您的Android设备。 我重新启动设备后,事情开始为我工作。

如果在Android 6中发生这种情况并编译target> = 23,请不要忘记我们现在使用运行时权限 。 所以在清单中给予权限是不够的。

使用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"); 

在android api> = 23

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

代替

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

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

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

我犯了包括两个错误:

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

和:

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

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