Recursive search for your own file system

I try to find an FSElement, which can be either a file or a directory to search in a file structure whose root is a local directory, and then tries to find, but it does not return the expected results to me. Can anyone suggest me where I am wrong.

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");
        }
+4
source share
1 answer

The problem you are facing is that when you search, if you come across a file that does not match the target file, you cause an error. You cannot throw an error through a recursive search without a helper method, you can do something similar instead.

This is completely untested, but should theoretically work.

    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;
}
+1

Source: https://habr.com/ru/post/1691295/


All Articles