我正在尝试搜索FSElement,它可以是文件或目录,在根目录为localroot目录的文件结构中查找,然后继续尝试查找,但它不会返回我预期的结果.任何人都可以建议我在哪里错了.
private FSElement getTargetFromName(String targetName) throws CommandNotExecutedException {
fsElement = localroot.getChildren();
Iterator children = fsElement.iterator();
while (children.hasNext()) {
FSElement child = children.next();
if (child.isDirectory()) {
if (child.getName().equals(targetName))
return child;
else {
localroot = (Directory) child;
return getTargetFromName(targetName);
}
} else if (child.getName().equals(targetName))
return child;
}
throw new CommandNotExecutedException("Destination file/dir not found");
}
最佳答案 您遇到的问题是,在搜索时,如果遇到与目标文件不匹配的文件,则会抛出错误.如果没有辅助方法,您将无法通过递归搜索抛出错误,而是可以执行此类操作.
这是完全未经测试的,但理论上应该有效.
private FSElement getTargetFromName (FSElement root, String targetName) {
Iterator children = root.iterator();
while (children.hasNext()) {
FSElement child = children.next();
if (child.getName().equals(targetName)) {
return child;
} else if (child.isDirectory()) {
FSElement searched = getTargetFromName(child, targetName);
if (searched != null) {
return searched;
}
}
}
return null;
}
如果你想让它抛出一个错误,你可以添加一个帮助方法,如:
public FSElement getTargetFromName (String targetName) throws CommandNotExecutedException {
FSElement file = getTargetFromName(localroot, targetName);
if (file == null) {
throw new CommandNotExecutedException("Destination file/dir not found");
}
return file;
}