Java 使用新文件()创建文件夹

Java 使用新文件()创建文件夹,java,file,directory,Java,File,Directory,我必须制作文件对象,我不知道它们目前是否存在。对于实际文件,没有问题: File file = new File("path+filename"); //File does not get generated which is fine. file.isDirectory() //is false :) 那么我如何创建一个文件对象,它是一个目录 File file = new File("path+foldername"); file.isDirectory = true; //doesn

我必须制作文件对象,我不知道它们目前是否存在。对于实际文件,没有问题:

File file = new File("path+filename"); //File does not get generated which is fine.
file.isDirectory() //is false :) 
那么我如何创建一个文件对象,它是一个目录

File file = new File("path+foldername"); 
file.isDirectory = true; //doesn't work oviously :(

要使用的方法是
.mdkir()
(或
.mkdirs()

但是,您需要检查返回代码,因为它们返回
boolean
s

但由于现在是2015年,我假设您使用Java 7+。因此,抛弃
文件
,忘掉它,改用java.nio.File:

final Path path = Paths.get("elements", "of", "path", "here");

Files.createDirectory(path);
Files.createDirectories(path);

让我们考虑下面的代码。在这里,最初我们没有文件或目录。这就是为什么退出()isFile()isDirectory()返回false。但是稍后,当我们使用mkdir()创建目录时,isDirectory返回true,因为我们已经成功创建了一个目录

    File file = new File("d:\\abc"); //This just creates a file object
    System.out.println(file.exists()); //This will return false
    System.out.println(file.isFile()); //This will return false
    System.out.println(file.isDirectory()); //This will return false

    file.mkdir(); //This will create a directory called abc
    System.out.println(file.exists()); //This will return true because a directory exists
    System.out.println(file.isFile()); //This will return false because we have created a directory called abc not a file
    System.out.println(file.isDirectory());//This will return true because we have just created a directory called abc
编辑:

file.isDirectory()
只有存在文件夹(目录)时才会返回true。例如,如果您在以下位置d:\sample已经有一个名为sample的文件夹。现在,创建一个名为:

File file = new File("d:\\sample");
如果你现在打电话

file.isDirectory()  //Returns true

它会变成现实。因为file对象指向一个有效且存在的文件夹。

是否使用Java 7+?问题是我不想创建文件夹。我只想要一个表示文件夹的对象,它在
上返回true。isDirectory