不论在windows还是linux下,仅凭字符串比较判断两个文件路径是否相等是不靠谱的。因为有link,Disk map等技术的存在,两个不同的路径有可能指向同一个文件。 NIO提供了Files.isSameFile方法可以准确判断两个路径是否指向同一个文件/文件夹. 以下示例是利用Files.isSameFile方法判断一个文件/文件夹是否为在另一个文件夹下的方法。
/**
* 判断sub是否与parent相等或在其之下<br>
* parent必须存在,且必须是directory,否则抛出{@link IllegalArgumentException}
* @param parent
* @param sub
* @return
* @throws IOException
*/
public static boolean sameOrSub(Path parent,Path sub) throws IOException{
if(null==parent)
throw new NullPointerException("parent is null");
if(!Files.exists(parent)||!Files.isDirectory(parent))
throw new IllegalArgumentException(String.format("the parent not exist or not directory %s",parent));
while(null!=sub) {
if(Files.exists(sub)&&Files.isSameFile(parent, sub))
return true;
sub=sub.getParent();
}
return false;
}
/**
* 判断sub是否在parent之下的文件或子文件夹<br>
* parent必须存在,且必须是directory,否则抛出{@link IllegalArgumentException}
* @param parent
* @param sub
* @return
* @throws IOException
* @see {@link #sameOrSub(Path, Path)}
*/
public static boolean isSub(Path parent,Path sub) throws IOException{
return (null==sub)?false:sameOrSub(parent,sub.getParent());
}