为什么mkdirs()方法无法正常工作?

3
在任何人将此标记为重复之前,我想让您知道我已经浏览了许多关于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权限。

下面是我的代码片段:

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+? - Elltz
我在LG G2上使用5.0.2。 - John Ernest Guadalupe
2个回答

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");
                }

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");
    }
 }

更多信息请点击这里这里

根据您的评论

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

您可以使用内部存储,并调用此 [getDir(java.lang.String, int)](http://developer.android.com/reference/android/content/Context.html#getDir(java.lang.String, int))

如果有帮助,请告诉我,先生。


但我不希望用户能够看到我将保存到文件夹中的文件。 - John Ernest Guadalupe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接