【问题标题】:make out of new File() a folder用 new File() 制作一个文件夹
【发布时间】:2015-04-01 16:04:33
【问题描述】:

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

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 :(

【问题讨论】:

  • 您使用的是 Java 7+ 吗?

标签: java file directory


【解决方案1】:

让我们考虑以下代码。在这里,最初我们没有文件或目录。这就是 exits()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

它会返回真。因为文件对象指向一个有效且存在的文件夹。

【讨论】:

  • 问题是我不想创建文件夹。我只想要一个代表文件夹的对象,它在.isDirectory 上返回 true
【解决方案2】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 2016-01-31
    • 2019-07-10
    • 2023-01-14
    • 1970-01-01
    相关资源
    最近更新 更多