存在從this Java教程由Oracle:檢查,如果一個文件或目錄在Java中
注意Files.exists(路徑)不等同於 Files.notExists(路徑)!
它們爲什麼不等同?就解釋而言,它並沒有進一步發展。 有沒有人知道更多關於這方面的信息? 在此先感謝!
存在從this Java教程由Oracle:檢查,如果一個文件或目錄在Java中
注意Files.exists(路徑)不等同於 Files.notExists(路徑)!
它們爲什麼不等同?就解釋而言,它並沒有進一步發展。 有沒有人知道更多關於這方面的信息? 在此先感謝!
!Files.exists()
回報:
true
如果該文件不存在或如果該文件存在Files.notExists()
返回其存在不能被確定
false
:
true
如果如果該文件存在或它的存在不能被確定從notExists
的Oracle docs的文件不存在
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)
回報TRUE
意味着它不存在或存在不能確定(2種可能性),Files.notExists(path)
返回TRUE
意味着它不存在(只有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
subexception NoSuchFileFound
拋出返回文件不存在,它是不是在IOException
導致沒有發現結果
您只需指定任何其他subexception絕對路徑,如果目錄/目錄不存在,它將創建drectory /目錄。
private void createDirectoryIfNeeded(String directoryName)
{
File theDir = new File(directoryName);
if (!theDir.exists())
theDir.mkdirs();
}
你好,這是嚴重的,我是PHP開發人員,並在Java中做一些項目。所以沒有簡單的方法來確定文件夾是否存在並且100%確定。我正在使用JDK 6.我認爲Java是成熟的語言... – BojanT 2014-10-08 13:45:45