How to create a directory in Android?

徘徊边缘 提交于 2019-12-01 04:09:50

问题


Everything is in the question. Here is my code :

    private void createDirectory(File currentDirectory) {
  File f = null;
  try {

   f = new File(currentDirectory.getCanonicalPath() + "/directory"
     + count);

   boolean success = f.mkdir();
   if (!success) {
    Toast.makeText(currentContext,
      f.getName() + " could not be created", 15).show();

   }
  } catch (IOException ioe) {
   Toast.makeText(currentContext,
     f.getName() + " could not be created", 15).show();
  }

  count++;
 }

I am writing a small file manager in Android and I would like to add the possibility to create a directory. There is no exception and the variable success always return false. Can someone tell me what is wrong my code??

Thx for your advice !!

[EDIT]

BTW, When the phone is in Developpement mode, does an application has a write access on the sdcard? I am programming on my phone (Acer liquid)


回答1:


You have to add this permission:

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

By the way, not sure how you are getting the SDcard directory... but it must be this way:

File sdDir = Environment.getExternalStorageDirectory();

It's important, because some programmers use to think that the SDCard is always /sdcard, but it could change.




回答2:


You're going to need to add

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

to your manifest file to tell Android to ask the user for your application to be allowed to.




回答3:


First, please use the File constructor that takes a File for your directory and a String for your desired subdirectory.

Beyond that, most likely you are attempting to create a directory where you are not allowed, either because:

  • currentDirectory does not exist, or
  • currentDirectory points to a place on the on-board flash storage where you are not allowed to write, or
  • currentDirectory points to a place on the external storage and you lack the WRITE_EXTERNAL_STORAGE permission



回答4:


instead of boolean success = f.mkdir(); use

boolean success = f.mkdirs();

that solved my problem (i used the same reference code as you and had the same issue).



来源:https://stackoverflow.com/questions/4776426/how-to-create-a-directory-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!