递归搜索自己的文件系统

拉贾特·阿南德(Rajat Anand):

我正在尝试搜索一个FSElement,它可以是文件或目录,以其根为localroot目录的文件结构查找,然后继续尝试查找,但它没有返回我的预期结果。谁能建议我我在哪里错。

private FSElement getTargetFromName(String targetName) throws CommandNotExecutedException {
            fsElement = localroot.getChildren();
            Iterator<FSElement> 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");
        }
扎卡里(Zachary):

您遇到的问题是,在搜索时,如果遇到与目标文件不匹配的文件,则会引发错误。没有辅助方法,您将无法通过递归搜索抛出错误,而是可以执行类似的操作。

这是完全未经测试的,但理论上应该可行。

    private FSElement getTargetFromName (FSElement root, String targetName) {
        Iterator<FSElement> 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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章