How to create Android directory automatically if it doesn't already exist

后端 未结 1 502
野的像风
野的像风 2021-02-12 15:49

I am creating a gallery app using a tutorial but get the following error:

abc directory path is not valid! Please set the image directory name AppConstant.java c

1条回答
  •  南笙
    南笙 (楼主)
    2021-02-12 16:23

    Here's how you create directories if they don't exist. Considering that directory is indeed a directory.

    // If the parent dir doesn't exist, create it
    if (!directory.exists()) {
        if (parentDir.mkdirs()) {
            Log.d(TAG, "Successfully created the parent dir:" + parentDir.getName());
        } else {
            Log.d(TAG, "Failed to create the parent dir:" + parentDir.getName());
        }
    }
    

    mkdirs() will also create missing parent directories (i.e. all directories that lead to directory).

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