在Java中检查文件或目录是否存在

6

来自Oracle的Java教程

注意!Files.exists(path)与Files.notExists(path)不等价。

为什么它们不等价?文中没有进一步的解释。有人了解更多信息吗?感谢您提前!

6个回答

10

!Files.exists()返回:

  • true 如果文件不存在或无法确定其是否存在
  • false 如果文件存在

Files.notExists()返回:

  • true 如果文件不存在
  • false 如果文件存在或无法确定其是否存在

3
在源代码中查看它们的区别,它们都做了完全相同的事情,但有一个主要区别。 notExist(...) 方法有一个额外的异常需要被捕获。

存在:

public static boolean exists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return true;
    } catch (IOException x) {
        // does not exist or unable to determine if file exists
        return false;
    }

}

不存在:

public static boolean notExists(Path path, LinkOption... options) {
    try {
        if (followLinks(options)) {
            provider(path).checkAccess(path);
        } else {
            // attempt to read attributes without following links
            readAttributes(path, BasicFileAttributes.class,
                           LinkOption.NOFOLLOW_LINKS);
        }
        // file exists
        return false;
    } catch (NoSuchFileException x) {
        // file confirmed not to exist
        return true;
    } catch (IOException x) {
        return false;
    }
}

结果如下所述:
  • !exists(...) 如果在检索文件时抛出IOException,则将文件标记为不存在。

  • notExists(...) 通过确保特定的IOException子异常NoSuchFileFound被抛出,并且没有其他的IOException子异常导致了未找到结果,将文件标记为不存在。


您好,这是认真的吗?我是PHP开发人员,正在使用Java进行一些项目。因此,确定文件夹是否存在并且确保100%的简单方法是不存在的。我正在使用JDK 6。我曾认为Java是成熟的语言... - BojanT

3

Files.exists中可以看出,返回结果为:

TRUE if the file exists; 
FALSE if the file does not exist or its existence cannot be determined.

Files.notExists返回的结果是:

TRUE if the file does not exist; 
FALSE if the file exists or its existence cannot be determined

如果!Files.exists(path)返回TRUE,则表示它不存在或者无法确定其存在(两种可能性),而对于Files.notExists(path)返回TRUE,则表示它不存在(只有一种可能性)。

结论是!Files.exists(path) != Files.notExists(path)2个可能性不等于1个可能性(请参考上述关于可能性的解释)。


1

如果目录不存在,您可以只指定绝对路径,它将创建该目录/目录。

private void createDirectoryIfNeeded(String directoryName)
{
File theDir = new File(directoryName); 
if (!theDir.exists())
    theDir.mkdirs();
}

1

来自Oracle文档notExists

请注意,此方法不是exists方法的补集。 如果无法确定文件是否存在,则这两种方法都返回false。...

我的强调。


1
 import java.io.File;

 // Create folder   
 boolean isCreate = new File("/path/to/folderName/").mkdirs();

 // check if exist 
 File dir = new File("/path/to/newFolder/");
 if (dir.exists() && dir.isDirectory()) {

 //the folder exist..
 }

还可以检查if Boolean变量 == True,但这种检查更好、更有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接