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

﹥>﹥吖頭↗ 提交于 2019-12-04 15:53:26

问题


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 class

Please visit the following link to see the entire tutorial's code as I am using the same code:

http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/

I found this code in Utils Class:

else { // image directory is empty Toast.makeText( _context, AppConstant.PHOTO_ALBUM + " is empty. Please load some images in it !", Toast.LENGTH_LONG).show(); }

    } else {
        AlertDialog.Builder alert = new AlertDialog.Builder(_context);
        alert.setTitle("Error!");
        alert.setMessage(AppConstant.PHOTO_ALBUM
                + " directory path is not valid! Please set the image directory name AppConstant.java class");
        alert.setPositiveButton("OK", null);
        alert.show();
    }

    return filePaths;

How can I create the missing directory programmatically instead of display this error dialog?


回答1:


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).



来源:https://stackoverflow.com/questions/25202977/how-to-create-android-directory-automatically-if-it-doesnt-already-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!