如何创建目录/文件夹?

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

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


当前回答

如果你想确保它被创建,那么:

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
    final boolean logsDirExists = logsDir.exists();
    assertThat(logsDirExists).isTrue();
}

因为mkDir()返回一个布尔值,如果你不使用这个变量,findbugs会为它哭泣。这也不好…

mkDir()只在mkDir()创建时返回true。 如果dir存在,它将返回false,因此要验证您创建的dir,如果mkDir()返回false,则只调用exists()。

assertThat()将检查结果,如果exists()返回false则失败。Ofc您可以使用其他东西来处理未创建的目录。

其他回答

如果你想确保它被创建,那么:

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
    final boolean logsDirExists = logsDir.exists();
    assertThat(logsDirExists).isTrue();
}

因为mkDir()返回一个布尔值,如果你不使用这个变量,findbugs会为它哭泣。这也不好…

mkDir()只在mkDir()创建时返回true。 如果dir存在,它将返回false,因此要验证您创建的dir,如果mkDir()返回false,则只调用exists()。

assertThat()将检查结果,如果exists()返回false则失败。Ofc您可以使用其他东西来处理未创建的目录。

对于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.io.File; /*输入下面的代码添加目录dir1或检查是否存在dir1,如果不存在,则创建dir2和dir3 */

    File filed = new File("C:\\dir1");
    if(!filed.exists()){  if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist");  }

    File filel = new File("C:\\dir1\\dir2");
    if(!filel.exists()){  if(filel.mkdir()){ System.out.println("directory is created");   }} else{ System.out.println("directory exist");  }

    File filet = new File("C:\\dir1\\dir2\\dir3");
    if(!filet.exists()){  if(filet.mkdir()){ System.out.println("directory is  created"); }}  else{ System.out.println("directory exist");  }

Mkdir vs mkdirs


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

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

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

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

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