File mkdirs() method not working in android/java

后端 未结 4 1112
不知归路
不知归路 2020-12-19 00:44

I\'ve been pulling out my hair on this for a while now. The following method is supposed to download a file, and save it to the location specified on the hard drive.

<
相关标签:
4条回答
  • 2020-12-19 00:56

    Please check with this, it may help you..

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

    enter tis permission in your manifest file.

    0 讨论(0)
  • 2020-12-19 00:57

    Further to Kevin Day's reply, there is another failure modality that previous posts did not mention. It is that even if you have android.permission.WRITE_EXTERNAL_STORAGE in your manifest, if you are trying to write to media such as /mnt/sdcard that is mounted externally as a USB gadget (i.e. you connected your device as an external disk to your PC with a USB cable) at the time you are trying to do the write, then you can't write to the /mnt/sdcard file system. In this case FILE.mkdir will return false. Obviously, if you are not checking the return code you wont see this problem until you get an IOException if you try to create a file in the directory that you think that you created. And if you don't create a file in this non-existent directory then the app will just silently fail.

    I make this mistake constantly when debugging Android apps - forget that I can't both have the sdcard mounted externally and at the same time have my app write to it.

    0 讨论(0)
  • 2020-12-19 01:05

    Are you sure that mkdirs is failing? Why don't you check the return value of the mkdirs call and log an error message if it returns false?

    if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()){
      log("Unable to create " + file.getParentFile());
    }
    

    I suspect that you might be surprised with what the file was...

    PS - and please do something with that error handler - at minimum, log the error. Catching Exception and doing a silent return is horrible practice.

    0 讨论(0)
  • 2020-12-19 01:10

    If you are writing contents to your SD card hope you have added android.permission.WRITE_EXTERNAL_STORAGE permission in your manifest

    0 讨论(0)
提交回复
热议问题