6

オラクルによるこのJavaチュートリアルから:

!Files.exists(path) は Files.notExists(path) と同等ではないことに注意してください。

なぜそれらは同等ではないのでしょうか? 説明の点ではこれ以上進みません。それについてもっと詳しい情報を知っている人はいますか?前もって感謝します!

4

6 に答える 6

10

!Files.exists()戻り値:

  • trueファイルが存在しないか、その存在を特定できない場合
  • falseファイルが存在する場合

Files.notExists()戻り値:

  • trueファイルが存在しない場合
  • falseファイルが存在するか、その存在を判別できない場合
于 2013-04-30T15:59:22.530 に答える
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)returnTRUEが存在しない、または存在を特定できない場合 (2 つの可能性)、Files.notExists(path)returnTRUEが存在しないことを意味する場合 (1 つの可能性のみ)。

結論!Files.exists(path) != Files.notExists(path)または2 possibilities not equals to 1 possibility(可能性については上記の説明を参照)。

于 2013-04-30T16:03:54.760 に答える
3

ソースコードで違いを調べると、どちらもまったく同じことを行いますが、1 つの大きな違いがあります。メソッドには、キャッチする追加の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

于 2013-04-30T16:07:00.830 に答える
1

OracleドキュメントからnotExists

このメソッドは exists メソッドを補完するものではないことに注意してください。ファイルが存在するかどうかを判断できない場合、両方のメソッドが false を返します。...

私のハイライト。

于 2013-04-30T15:59:40.787 に答える
1

ディレクトリ/ディレクトリが存在しない場合は、絶対パスを指定するだけで、drectory/ディレクトリが作成されます。

private void createDirectoryIfNeeded(String directoryName)
{
File theDir = new File(directoryName); 
if (!theDir.exists())
    theDir.mkdirs();
}
于 2014-09-04T16:50:10.217 に答える