2016-03-01 52 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); 
...