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

use*_*970 19 android android-sdcard

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

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

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

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

我在UtilsClass中找到了这段代码:

else {//图像目录为空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;
Run Code Online (Sandbox Code Playgroud)

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

Sim*_*mas 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

mkdirs()还将创建缺少的父目录(即所有导致的目录directory).