オラクルによるこのJavaチュートリアルから:
!Files.exists(path) は Files.notExists(path) と同等ではないことに注意してください。
なぜそれらは同等ではないのでしょうか? 説明の点ではこれ以上進みません。それについてもっと詳しい情報を知っている人はいますか?前もって感謝します!
!Files.exists()
戻り値:
true
ファイルが存在しないか、その存在を特定できない場合false
ファイルが存在する場合Files.notExists()
戻り値:
true
ファイルが存在しない場合false
ファイルが存在するか、その存在を判別できない場合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
(可能性については上記の説明を参照)。
ソースコードで違いを調べると、どちらもまったく同じことを行いますが、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
のOracleドキュメントからnotExists
。
このメソッドは exists メソッドを補完するものではないことに注意してください。ファイルが存在するかどうかを判断できない場合、両方のメソッドが false を返します。...
私のハイライト。
ディレクトリ/ディレクトリが存在しない場合は、絶対パスを指定するだけで、drectory/ディレクトリが作成されます。
private void createDirectoryIfNeeded(String directoryName)
{
File theDir = new File(directoryName);
if (!theDir.exists())
theDir.mkdirs();
}