2 回答
TA贡献1866条经验 获得超5个赞
您可以使用一种检查候选路径是否以必填父路径开头的方法。看来Java 7 nio对此提供了很好的支持。
这是实现此想法的方法:
/**
* Check if a candidate path starts with a mandatory parent path
* @param mandatoryParentPath Mandatory parent path
* @param candidate Candidate path which should be under the mandatory parent path
* @return {@code true} if a candidate path starts with a mandatory parent path, else {@code false}
*/
/**
* Check if a candidate path starts with a mandatory parent path
* @param mandatoryParentPath Mandatory parent path
* @param candidate Candidate path which should be under the mandatory parent path
* @return {@code true} if a candidate path starts with a mandatory parent path, else {@code false}
*/
public static boolean absoluteStartsWith(Path mandatoryParentPath, Path candidate) throws IOException {
Objects.requireNonNull(mandatoryParentPath, "Mandatory parent path should not be null");
Objects.requireNonNull(candidate, "Candidate path should not be null");
Path path = candidate.toRealPath();
System.out.println(" " + candidate); // debugging code
return path.startsWith(mandatoryParentPath.toAbsolutePath());
}
这是验证上述方法的简单测试:
public static void main (String[] args) throws java.lang.Exception
{
Path root = Paths.get("d:/work");
System.out.println(absoluteStartsWith(root, root.resolve("/tmp")));
System.out.println(absoluteStartsWith(root, root.resolve("..")));
System.out.println(absoluteStartsWith(root, root.resolve("ems")));
}
这会在我的机器上打印出来:
d:\tmp
false
d:\work\..
false
d:\work\ems
true
注意:如果候选路径之一不存在,则上述absoluteStartsWith方法将引发IOException 。
添加回答
举报