Android 创建目录

Android create directory

我正在尝试在 Android 设备的 SD 卡上的下载目录中创建一个文件夹。我已在清单中声明 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这是我的代码:

String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        Log.e("file writer", "Directory not writeable");
        Toast.makeText(this, "Not writeable.",
                Toast.LENGTH_SHORT).show();
    }

    File dir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "myfolder");
    dir.mkdirs();
    if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); }

我收到 "directory not created" 错误,显然没有我想要的文件夹。

你试过吗?

String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
    Log.e("file writer", "Directory not writeable");
    Toast.makeText(this, "Not writeable.",
            Toast.LENGTH_SHORT).show();
}else{

File dir = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS), "myfolder");
dir.mkdirs();
if (!dir.mkdirs()) { Log.e("file writer", "Directory not created"); } }

要在 Android 6+ 中获得许可,您应该询问用户,试试这个

        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // Show an expanation to the user *asynchronously* -- don't block this thread waiting for the user's response! After the user sees the explanation, try again to request the permission.
        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an app-defined int constant. The callback method gets the result of the request.
        }
    }

试试这个代码

 File rootPath = new File(Environment.getExternalStorageDirectory(), "Download/myfolder");
 if (!rootPath.exists())
        rootPath.mkdirs();

希望有用