如何创建目录/文件夹?

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

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


当前回答

public class Test1 {
    public static void main(String[] args)
    {
       String path = System.getProperty("user.home");
       File dir=new File(path+"/new folder");
       if(dir.exists()){
           System.out.println("A folder with name 'new folder' is already exist in the path "+path);
       }else{
           dir.mkdir();
       }

    }
}

其他回答

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

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您可以使用其他东西来处理未创建的目录。

只是想向每个调用File.mkdir()或File.mkdirs()的人指出,要小心File对象是目录而不是文件。例如,如果你为路径/dir1/dir2/file.txt调用mkdirs(),它将创建一个名为file.txt的文件夹,这可能不是你想要的。如果你正在创建一个新文件,同时也想自动创建父文件夹,你可以这样做:

            File file = new File(filePath);
            if (file.getParentFile() != null) {
                file.getParentFile().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.

下面的方法可以做你想做的事情,只要确保你检查了mkdir() / mkdirs()的返回值

private void createUserDir(final String dirName) throws IOException {
    final File homeDir = new File(System.getProperty("user.home"));
    final File dir = new File(homeDir, dirName);
    if (!dir.exists() && !dir.mkdirs()) {
        throw new IOException("Unable to create " + dir.getAbsolutePath();
    }
}

虽然这个问题已经有了答案。我想多放点东西,比如。 如果存在与您试图创建的目录名称相同的文件,则会提示错误。为将来的访客准备的。

public static void makeDir()
{
    File directory = new File(" dirname ");
    if (directory.exists() && directory.isFile())
    {
        System.out.println("The dir with name could not be" +
        " created as it is a normal file");
    }
    else
    {
        try
        {
            if (!directory.exists())
            {
                directory.mkdir();
            }
            String username = System.getProperty("user.name");
            String filename = " path/" + username + ".txt"; //extension if you need one

        }
        catch (IOException e)
        {
            System.out.println("prompt for error");
        }
    }
}