2014-09-08 5 views
0

answer을 기반으로 지정된 문자열이 들어있는 모든 디렉터리와 하위 디렉터리를 찾으려고합니다.이름을 기반으로하는 하위 디렉터리 및 디렉터리 찾기

function fileNames = findAllDirectories(directory, wildcardPattern) 

    import org.apache.commons.io.filefilter.*; 
    import org.apache.commons.io.FileUtils; 
    import java.io.File; 

    files = FileUtils.listFilesAndDirs(File(directory),... 
             NotFileFilter(TrueFileFilter.INSTANCE),... 
             DirectoryFileFilter.DIRECTORY); 

    fileNames = cellfun(@(f) char(f.getCanonicalPath()),... 
         cell(files.toArray()),... 
         'uniformOutput', false); 
end 

을 나는 이름 패턴에서 검색을 지정하려면 어떻게 : 지금은 (문자열 패턴이 구현되지 않고 그게 내가하고 싶은거야) 모든 디렉토리 및 하위 디렉토리를 보여 다음 코드를했습니다 디렉토리/하위 디렉토리 이름? 나는 다음과 같은 디렉토리 구조가있는 경우

예를 들어, :

C:\aaa 
C:\aaa\aaa 
C:\aaa\bbb 
C:\aaa\ccc 
C:\aaa\bbb\ccc 
C:\aaa\ddd 
C:\aaa\ddd\bbb 

내가 findAllDirectories('C:\aaa','ccc')를 호출 그 결과는 같아야합니다

C:\aaa\ccc 
C:\aaa\bbb\ccc 

답변

1

는 사용하지 않는이 기능을 사용해보십시오 모든 Java 라이브러리 :

function dirPaths = findAllDirectories(baseDirectory, wildcardPattern) 

dirPaths = recFindAllDirectories(baseDirectory); 

    function matchedDirPaths = recFindAllDirectories(searchPath) 
     files = dir(searchPath); % gets a struct array of the files and dirs in the dir. 
     files = files(3:end); % removes '.' and '..' 
     dirs = files([files.isdir]); % filters the results to directories only. 
     dirNames = {dirs.name}; % takes the names of the directories 
     matchedNamesIdxs = ~cellfun(@isempty, regexp(dirNames, wildcardPattern)); % applys the pattern search. 
     matchedDirPaths = fullfile(searchPath, dirNames(matchedNamesIdxs)); % concats to get a full path to the matched directories. 
     for i = 1:length(dirNames) 
      currMatchedDirPaths = recFindAllDirectories(fullfile(searchPath, dirNames{i})); % recursively calls the function for the subdirectories. 
      matchedDirPaths = [matchedDirPaths currMatchedDirPaths]; % adds the output of the recursive call to the current call's output. 
     end 
    end 

end 

디렉토리 구조에서 동일한 호출 wi LL 출력 셀 어레이 :

는 'C : \ AAA \ CCC' 'C : \ AAA \ BBB \ CCC'

+0

그것은 잘 작동합니다. 재귀 함수를 사용하지 않고 간단한 코드를 이해하기 위해 java를 사용하고 싶었습니다. 이것을 Java로 구현하는 방법을 알고 있습니까? –

+0

Java로 작성한 지 오래되었습니다. 죄송합니다. 이 코드에 대해 질문이 있으시면 언제든지 물어보십시오. 재귀 호출은 쉬운 구현을위한 것입니다. 그러나이 경우에는이 함수를 비 재귀 적으로 다시 구현하는 것이 어렵지 않아야한다고 생각합니다. – Shaked

관련 문제