如何创建目录/文件夹?

一旦我测试了System.getProperty("user.home");

我必须创建一个目录(目录名“新文件夹”)当且仅当新文件夹不存在时。


当前回答

您可以尝试FileUtils#forceMkdir

FileUtils.forceMkdir("/path/directory");

这个库有很多有用的函数。

其他回答

Mkdir vs mkdirs


如果要创建单个目录,请使用mkdir

new File("/path/directory").mkdir();

如果想要创建文件夹结构的层次结构,请使用mkdirs

 new File("/path/directory").mkdirs();

您可以尝试FileUtils#forceMkdir

FileUtils.forceMkdir("/path/directory");

这个库有很多有用的函数。

这是java的一个吸引力,使用短路或'||',测试目录的存在,并为您制作目录

public File checkAndMakeTheDirectory() {
    File theDirectory = new File("/path/directory");
    if (theDirectory.exists() || theDirectory.mkdirs())
        System.out.println("The folder has been created or has been already there");
    return theDirectory;
}

如果If的第一部分为真,它不会运行第二部分,如果第一部分为假,它也会运行第二部分

对于java 7及以上版本:

Path path = Paths.get("/your/path/string");
Files.createDirectories(path);

在创建之前检查目录或文件是否存在似乎是不必要的,from createDirectories javadocs:

Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored. If this method fails, then it may do so after creating some, but not all, of the parent directories.

new File("/path/directory").mkdirs();

这里的“directory”是你想要创建/存在的目录的名称。