【问题标题】:Why is the mkdirs() method not working?为什么 mkdirs() 方法不起作用?
【发布时间】:2015-11-07 04:31:46
【问题描述】:

在有人将此标记为重复之前,我想让您知道,我已经解决了很多关于 SO 上的 mkdirs() 方法的问题,但没有一个对我有用,所以我相信我有一个特殊情况这个问题值得一问。

我尝试使用mkdir(),将目录File的实例化更改为

new File(Environment.getExternalStorageDirectory())
new File(Environment.getExternalStorageDirectory().getAbsolutePath())
new File(Environment.getExternalStorageDirectory(), "Directory")
new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Directory")
new File(Environment.getExternalStorageDirectory().toString + "/Directory")

没有任何效果。

注意:我的清单中也有 WRITE_EXTERNAL_STORAGE 权限。

这是我的代码 sn-p:

File rootDirectory = new File(Environment.getExternalStorageDirectory(), getActivity().getPackageName());

File directory = new File(rootDirectory, "Directory");
if (!directory.exists()) {
    if(directory.mkdirs()){
       Log.d("log", "exists");
    } else {
       Log.d("log", "not exists");
    }
 }

【问题讨论】:

  • 你用过什么api版本? 2.3 还是 18+?
  • 我在 LG G2 上使用 5.0.2

标签: android file mkdirs


【解决方案1】:

使用这个

File rootDirectory = new File(Environment.getExternalStorageDirectory(), 
      new File(Environment.DIRECTORY_DOCUMENTS, getActivity().getPackageName()));
   // if you target below api 19 use this => DIRECTORY_DOWNLOADS
  // now your old code follows life is good
File directory = new File(rootDirectory, "Directory");
if (!directory.exists()) {
    if(directory.mkdirs()){
       Log.d("log", "exists");
    } else {
       Log.d("log", "not exists");
    }
 }

更多信息herehere

来自您的评论

但我不希望用户能够看到我要保存到文件夹中的文件

您可以使用internal memory 并调用它 [getDir(java.lang.String, int)](http://developer.android.com/reference/android/content/Context.html#getDir(java.lang.String, int))

如果有帮助请告诉我

【讨论】:

  • 但我不希望用户看到我要保存到文件夹中的文件
【解决方案2】:

mkdirs 创建完整的文件夹树,mkdir 只创建完整文件夹树路径中的最后一个文件夹

使用这样的代码:

String foldername = "HelloWorld";
                 File dir = new File(Environment.getExternalStorageDirectory() + "/" + foldername);
                if (dir.exists() && dir.isDirectory()) {
                    Log.d("log", "exists");
                } else {
                    //noinspection ResultOfMethodCallIgnored
                    dir.mkdir();
                    Log.d("log", "created");
                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 2023-03-03
    • 1970-01-01
    • 2013-01-22
    • 2018-08-06
    • 2012-01-14
    • 2015-12-10
    • 1970-01-01
    相关资源
    最近更新 更多