如何在 Android 4.4.2(Kitkat) API 级别 19 的外部 SD 卡中创建文件夹

How to Create a folder in external sdcard in Android 4.4.2(Kitkat) API level 19

我在 android 4.4.2 版本中尝试了很多在 SD 卡中创建文件夹的方法。 我尝试以下代码

 String dirName="Test";
   File file = new File(Environment.getExternalStorageDirectory(), dirName);
        boolean status = file.mkdir();
                    if (status)
                        Toast.makeText(MainActivity.this,
                                "Directory created successfully", Toast.LENGTH_SHORT)
                                .show();
                        else
                            Toast.makeText(MainActivity.this, "Directory create failed",
                                    Toast.LENGTH_SHORT).show();

但它会在内部存储中创建一个文件夹。

我尝试另一个代码是

  String path=System.getenv("SECONDARY_STORAGE");
                File file=new File(path +"/Test123");
                file.mkdir();

它在 android 4.1 的外部 SDCARD 中创建了一个文件夹,但在 android 4.4.2

中没有

那么我如何在 android 4.4.2 的外部 sdcard 中创建一个文件夹? 如果有人知道请帮助我..

提前致谢

这应该是不言自明的。

String folderName = "NewFolder";

        File file = new File(Environment.getExternalStorageDirectory(),
                folderName);
        if (!file.exists()) {
            file.mkdirs();
        }

确保您已在清单中添加 WRITE_EXTERNAL_STORAGE 权限。

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

感谢Dhaval

文档指出

Applications should not directly use this top-level directory, in order to avoid polluting the user's root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled.

其中 top-level directory 表示 Enviroment.getExternalStorageDirectory()

的 return 值

使用getExternalFilesDir你将拥有

 File file = new File (getExternalFilesDir(null), dirName);
 if (!file.exists()) {
   boolean status = file.mkdir();
   if (status) {
        Toast.makeText(MainActivity.this, "Directory created successfully", Toast.LENGTH_SHORT).show();
   } else {
        Toast.makeText(MainActivity.this, "Directory create failed", Toast.LENGTH_SHORT).show();
   }
 }

你还应该知道,如果目录已经存在,mkdir() returns false