【发布时间】:2013-04-24 14:49:41
【问题描述】:
来自thisoracle的java教程:
注意 !Files.exists(path) 不等同于 Files.notExists(路径)。
为什么它们不相等?它在解释方面没有进一步说明。 有人知道更多关于这方面的信息吗? 提前致谢!
【问题讨论】:
来自thisoracle的java教程:
注意 !Files.exists(path) 不等同于 Files.notExists(路径)。
为什么它们不相等?它在解释方面没有进一步说明。 有人知道更多关于这方面的信息吗? 提前致谢!
【问题讨论】:
!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) 返回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;
}
}
因此差异如下:
如果在尝试检索文件时抛出IOException,!exists(...) 将返回文件不存在。
notExists(...) 通过确保抛出特定的 IOException 子异常 NoSuchFileFound 并且它不是导致未找到结果的 IOException 上的任何其他子异常,将文件返回为不存在
【讨论】:
【讨论】:
你可以只指定绝对路径,如果目录/目录不存在,它会创建目录/目录。
private void createDirectoryIfNeeded(String directoryName)
{
File theDir = new File(directoryName);
if (!theDir.exists())
theDir.mkdirs();
}
【讨论】:
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 variable == True,不过这个检查更好更有效。
【讨论】: