2016-03-01 53 views
0

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

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); 
      } 
     } 
    } 
} 

我们的目标是能够找到(文件)的路径递归目录树中,而这些返回谁调用的类/调用的方法。

+0

是否期望为了有在结果的一个或多个发现路径? – aglassman

回答

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 
} 
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); 
...