如果Android目录尚不存在,如何自动创建

时间:2014-08-08 11:55:43

标签: android android-sdcard

我正在使用教程创建一个图库应用,但会收到以下错误:

abc目录路径无效!请设置图像目录名称AppConstant.java类

请使用以下链接查看整个教程的代码,因为我使用相同的代码:

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

我在Utils Class:

中找到了这段代码

其他{                 //图像目录为空                 Toast.makeText(                         _context,                         AppConstant.PHOTO_ALBUM                                 +"是空的。请加载一些图像!",                         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;

如何以编程方式创建缺少的目录,而不是显示此错误对话框?

1 个答案:

答案 0 :(得分:12)

如果目录不存在,您可以创建目录。考虑到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()还会创建缺少的父目录(即导致directory的所有目录)。