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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16304034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:35:12  来源:igfitidea点击:

Checking if a file or directory exists in Java

javafileexists

提问by Rollerball

From thisjava tutorial by oracle:

来自oracle的这个java教程:

Note that !Files.exists(path) is not equivalent to Files.notExists(path).

请注意,!Files.exists(path) 不等同于 Files.notExists(path)。

Why would they not be equivalent? it does not go any further in terms of explanation. Does anybody know more information about that? Thanks in advance!

为什么它们不相等?它没有进一步解释。有没有人知道更多相关信息?提前致谢!

回答by Adam Stelmaszczyk

!Files.exists()returns:

!Files.exists()返回:

  • trueif the file does not exist or its existence cannot be determined
  • falseif the file exists
  • true如果文件不存在或无法确定其存在
  • false如果文件存在

Files.notExists()returns:

Files.notExists()返回:

  • trueif the file does not exist
  • falseif the file exists or its existence cannot be determined
  • true如果文件不存在
  • false如果文件存在或无法确定其存在

回答by Crazenezz

As we see from Files.existsthe return result is:

正如我们从Files.exists看到的,返回结果是:

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

And from Files.notExiststhe return result is:

Files.notExists返回结果是:

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

So if !Files.exists(path)return TRUEmeans it not exists or the existence cannot be determined (2 possibilities) and for Files.notExists(path)return TRUEmeans it not exists (just 1 possibility).

因此,如果!Files.exists(path)返回TRUE意味着它不存在或存在无法确定(2 种可能性),而Files.notExists(path)返回TRUE意味着它不存在(只有 1 种可能性)。

The conclusion !Files.exists(path) != Files.notExists(path)or 2 possibilities not equals to 1 possibility(see the explanation above about the possibilities).

结论!Files.exists(path) != Files.notExists(path)2 possibilities not equals to 1 possibility(参见上面关于可能性的解释)。

回答by Skepi

Looking in the source code for the differences they both do the exact same thing with 1 major difference. The notExist(...)method has an extra exception to be caught.

查看源代码中的差异,他们都做完全相同的事情,但有 1 个主要差异。该notExist(...)方法有一个额外的异常要捕获。

Exist:

存在:

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;
    }

}

Not Exist:

不存在:

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;
    }
}

As a result the differences are as follow:

因此,差异如下:

  • !exists(...)returns the file as non existent if an IOExceptionis thrown when attempting to retrieve the file.

  • notExists(...)returns the file as non existent by making sure the specific IOExceptionsubexception NoSuchFileFoundis thrown and that it isn't any other subexception on IOExceptioncausing the not found result

  • !exists(...)如果IOException在尝试检索文件时抛出an ,则将文件返回为不存在。

  • notExists(...)通过确保抛出特定的IOExceptionNoSuchFileFound异常并且它不是IOException导致未找到结果的任何其他子异常,将文件返回为不存在

回答by user2186465

You can just specify the absolute path, if the directory/directories doesn't exits, it will create the drectory/directories.

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

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

回答by Gavriel Cohen

 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..
 }

Can also check if Boolean variable == True, but this check is better and more effective.

也可以检查if Boolean variable == True,但是这个检查更好更有效。

回答by OldCurmudgeon

From the Oracle docsof notExists.

甲骨文的文档notExists

Note that this method is not the complement of the exists method. Where it is not possible to determine if a file exists or not then both methods return false. ...

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

My highlighting.

我的突出显示。