2012-05-14 3 views
5

루트 디렉토리에있는 파일을 찾으려고합니다. 하위 디렉토리입니다.파일 검색 재귀

1 단계 - 지정된 경로에서 디렉토리를 찾습니다. 2 단계 - 위의 디렉토리가 발견되면 하위 디렉토리 중 하나에서 파일을 찾습니다.

여기에 재귀 적으로 검색하는 아래의 코드 조각을 사용합니다. 자, 문제는 위의 두 가지 요구 사항을 모두 충족 할 때 재귀를 중단하는 방법입니다.

boolean bFileFound = false; 
File fileFound  = null; 

private void findFile(File aFile, String sDir){ 

    String filePath = aFile.getAbsolutePath(); 

    if(aFile.isFile() && filePath.contains(sDir)){ 

       if(aFile.getName().contains("test2.adv")){ 
        Log.d(TAG, "[FILE] " + aFile.getName()); 
        fileFound = aFile; 
        bFileFound = true; 
       } 

      // return true; 
    }else if(aFile.isDirectory()){ 

     String sDirName = aFile.getName(); 
     Log.d(TAG, "[DIR] " + sDirName); 

     if(sDirName.contains(sDir)){ 

      Log.d(TAG, "Found the directory..& Absolute Path = " + aFile.getAbsolutePath()); 
      sDir = sDirName; 
     } 

     File[] listFiles = aFile.listFiles(); 

     if(listFiles != null){ 

      for(int i = 0; i < listFiles.length; i++){ 

       if(bFileFound) 
        return; 

      findFile(listFiles[ i ], sDir); 
      } 
     }else{ 

      Log.d(TAG, " [ACCESS DENIED]"); 
     } 
    } 

    // return null; 
} 

감사합니다, DK 이제

답변

6
/** 
* Search file a file in a directory. Please comment more here, your method is not that standard. 
* @param file the file/folder where to look our file for. 
* @param sDir a directory that must be in the path of the file to find 
* @param toFind the name of file we are looking for. 
* @return the file we were looking for. Null if no such file could be found. 
*/ 
private File findFile(File aFile, String sDir, String toFind){ 
    if(aFile.isFile() && 
      aFile.getAbsolutePath().contains(sDir) && 
      aFile.getName().contains(toFind)) { 
         return aFile; 
     } else if(aFile.isDirectory()) { 
     for(File child : aFile.listFiles()){ 
      File found = findFile(child, sDir, toFind); 
        if(found != null) { 
         return found; 
        }//if 
     }//for 
    }//else 
    return null; 
}//met 

, 당신은 findFile를 호출 세 번째 PARAM으로 "test2.adv"를 전달합니다. 하드 코딩보다 재미 있습니다.

또한 여러 파일이 검색과 일치 할 수 있습니다.이 함수는 잘 처리하지 못하므로 첫 번째 파일을 반환합니다.

+0

감사 Sincolas은 .. 그건 awsome ... – codersnet

0

나는이 문제를 해결하기 위해 FileFilter과 재귀 적으로 다른 검색 방법을 사용하여 약간 다른 접근 방식을 취했습니다. 제 경우에는 파일 이름이 중요하지 않은 ".json"확장자를 가진 파일을 찾고있었습니다.

먼저는, 재귀 검색 다음

/** 
* A {@link FileFilter} implementation that checks recursively files of a 
* specified fileName or extension string 
*/ 
public class FileExtensionFinder implements FileFilter { 
    private final String fileName; 
    private final List<File> foundFiles; 

    /** 
    * Constructor for FileExtensionFinder 
    * @param fileName string of the filename or extension being searched for 
    */ 
    public FileExtensionFinder(String fileName) { 
     this.fileName = fileName; 
     this.foundFiles = new ArrayList<>(); 
    } 

    @Override 
    public boolean accept(File pathname) { 
     // accept anything that is a folder or matches the fileName string 
     return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(fileName); 
    } 

    /** 
    * Searches recursively for all files with the provided filename/extension string 
    * @param filesArray an array of files (including folders) to iterate over 
    */ 
    public List<File> findFiles(File... filesArray) { 
     for (File file : filesArray) { 
      if (file.isDirectory()) { 
       findFiles(file.listFiles(this)); 
      } else if (file.getName().toLowerCase().endsWith(fileName)) { 
       foundFiles.add(file); 
      } 
     } 
     return foundFiles; 
    } 
} 

을 파일 이름을 보유하는 FileFilter 구현 클래스를 작성하고 수행 사용법은 매우 간단하다 :

File fileLocation = // get your file here ... 
List<File> foundFiles = new FileExtensionFinder(".json").findFiles(fileLocation);