【问题标题】:Finding subdirectories and directories based on name根据名称查找子目录和目录
【发布时间】:2014-09-08 17:02:05
【问题描述】:

基于此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

【问题讨论】:

    标签: java apache matlab loops directory


    【解决方案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
    

    使用您的目录结构,相同的调用将输出元胞数组:

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

    【讨论】:

    • 效果很好。我想使用 java 以避免使用递归函数并有一个更简单的代码来理解。你知道如何用 Java 实现吗?
    • 很久没用Java写了,抱歉。如果您对此代码有任何疑问,请随时提出。递归调用只是为了便于实现,尽管我认为在这种情况下,将这个函数重新实现为非递归应该不难。
    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多