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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25202977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:12:29  来源:igfitidea点击:

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

androidandroid-sdcard

提问by user3739970

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

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

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/

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

I found this code in UtilsClass:

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

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

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;

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

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

回答by Simas

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

如果目录不存在,请按照以下方法创建目录。考虑到这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).

mkdirs()还将创建缺少的父目录(即所有指向 的目录directory)。