ale*_*oot 8 java file file-exists
我想检查给定的String是文件还是目录,我已经尝试了File类的方法isFile()和isDirectory(),但问题是如果目录或文件不存在,这些方法返回false ,因为如javadoc中所述:
isFile():
当且仅当此抽象路径名表示的文件存在并且是普通文件时才返回true; 否则是假的
isDirectory():
当且仅当此抽象路径名表示的文件存在且为目录时才为true; 否则是假的
基本上我需要两个没有现有条款的方法 ......
所以我想在多平台上下文中测试给定的字符串是否符合目录格式或符合文件格式(因此,应该适用于Windows,Linux和Mac Os X).
是否存在提供这些方法的库?什么可能是这些方法的最佳实现?
UPDATE
对于字符串,如果不存在具有该路径的文件,则默认情况下应该将(无扩展名)的字符串标识为目录.
所以我想在多平台上下文中测试给定的字符串是否符合目录格式或符合文件格式(因此,应该适用于Windows,Linux和Mac Os X).
在Windows中,目录可以具有扩展名,并且文件不需要具有扩展名.所以,你不能仅仅通过查看字符串来判断.
如果您强制执行规则,即目录没有扩展名,并且文件始终具有扩展名,则可以通过查找扩展名来确定目录和文件之间的差异.
根据您的更新,听起来您知道自己想要什么:如果路径不存在并且路径具有扩展名,则它是一个文件,如果不存在,则它是一个目录。像这样的东西就足够了:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19691 次 |
| 最近记录: |