保留递归方法调用之间的值

时间:2016-03-01 17:29:13

标签: java

在下面的代码片段中,如何保留找到的(路径)值并将其返回给调用方法的类?

public void searchFile(Path searchFrom, String match) throws IOException {
    try(DirectoryStream<Path> SearchResult = Files.newDirectoryStream(searchFrom)) {
        for(Path check : SearchResult) {
            if(!Files.isDirectory(check) && check.toString().contains(match)) {
                System.out.println(check.toString());
            } else if(Files.isDirectory(check)) {
                searchFile(check, match);
            }
        }
    }
}

目标是能够在目录树中递归地查找(文件)路径,并将这些路径返回给调用/调用该方法的类。

2 个答案:

答案 0 :(得分:0)

找到时返回路径:

public Path searchFile(Path searchFrom, String match) throws IOException {
    try(DirectoryStream<Path> SearchResult = Files.newDirectoryStream(searchFrom)) {
        for(Path check : SearchResult) {
            if(!Files.isDirectory(check) && check.toString().contains(match)) {
                return check;
            } else if(Files.isDirectory(check)) {
                Path found=searchFile(check, match);
                if (found!=null){
                  return found;
                }
            }
        }
    }
    return null; // not found
}

答案 1 :(得分:0)

传递第三个参数并将其作为返回值, 假设您需要多个返回值 (而不仅仅是在JP Moresmau答案中演示的第一个)。

例如

public class Blammy
{
    private List<Path> kapow = new LinkedList<Path>();

    public addPath(final Path newPath)
    {
        kapow.add(newPath);
    }

    public List<Path> getKapow()
    {
        return kapow;
    }
}

public void searchFile(
    final Path searchFrom,
    final String match,
    final Blammy blammy) ...
...
    // Instead of System.out.println(check.toString()); do this:
    blammy.addPath(check);
...