我想检查给定的String是文件还是目录,我尝试了File类的isFile()和isDirectory()方法,但是问题是,如果目录或文件不存在,则这些方法返回false ,因为如javadoc中所述:
isFile():
当且仅当此抽象路径名表示的文件存在且为普通文件时,才返回true;否则为true。否则为假
isDirectory():
当且仅当此抽象路径名表示的文件存在并且为目录时,才返回true;否则,则返回true。否则为假
基本上我需要两种不存在条件的方法 ...
因此,我想测试给定的字符串是否在多平台上下文中符合目录格式或文件格式(因此,应在Windows,Linux和Mac OS X上运行)。
是否存在提供这些方法的某些库?这些方法的最佳实现是什么?
更新
如果字符串不存在,则默认情况下两者都可以(不带扩展名)应标识为目录。
根据您的更新,听起来好像您知道要什么:如果路径不存在,并且路径具有扩展名,则为文件;如果不具有扩展名,则为目录。这样的事情就足够了:
private boolean isPathDirectory(String myPath) {
File test = new File(myPath);
// check if the file/directory is already there
if (!test.exists()) {
// see if the file portion it doesn't have an extension
return test.getName().lastIndexOf('.') == -1;
} else {
// see if the path that's already in place is a file or directory
return test.isDirectory();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句