来自Oracle的Java教程:
注意!Files.exists(path)与Files.notExists(path)不等价。
为什么它们不等价?文中没有进一步的解释。有人了解更多信息吗?感谢您提前!
!Files.exists()
返回:
true
如果文件不存在或无法确定其是否存在false
如果文件存在Files.notExists()
返回:
true
如果文件不存在false
如果文件存在或无法确定其是否存在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
子异常导致了未找到结果,将文件标记为不存在。
从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
,则表示它不存在或者无法确定其存在(两种可能性),而对于Files.notExists(path)
返回TRUE
,则表示它不存在(只有一种可能性)。
结论是!Files.exists(path) != Files.notExists(path)
或2个可能性不等于1个可能性
(请参考上述关于可能性的解释)。
如果目录不存在,您可以只指定绝对路径,它将创建该目录/目录。
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变量 == True
,但这种检查更好、更有效。