如何创建目录/文件夹?

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

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


当前回答

Mkdir vs mkdirs


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

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

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

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

其他回答

Mkdir vs mkdirs


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

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

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

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

创建单个目录。 新文件(C: \ \ Directory1) .mkdir (); 创建一个名为“Directory2”的目录及其所有子目录“Sub2″”和“Sub-Sub2″”。 新文件(“C: \ \ Directory2 \ \ Sub2 \ \ Sub-Sub2”).mkdirs ()

源码:这个完美的教程,你也找一个使用的例子。

对于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.

在Java 7中,您可以使用Files.createDirectories()。

例如:

Files.createDirectories(Paths.get("/path/to/directory"));

整洁干净:

import java.io.File;

public class RevCreateDirectory {

    public void revCreateDirectory() {
        //To create single directory/folder
        File file = new File("D:\\Directory1");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        //To create multiple directories/folders
        File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
        if (!files.exists()) {
            if (files.mkdirs()) {
                System.out.println("Multiple directories are created!");
            } else {
                System.out.println("Failed to create multiple directories!");
            }
        }

    }
}