Java 基于名称查找子目录和目录
基于此,我尝试查找包含指定字符串的所有目录和子目录。现在我有以下代码,其中显示了所有目录和子目录(没有实现字符串模式,这就是我想要的): 如何指定在目录/子目录名称中搜索名称模式 例如,如果我有以下目录结构:Java 基于名称查找子目录和目录,java,apache,matlab,loops,directory,Java,Apache,Matlab,Loops,Directory,基于此,我尝试查找包含指定字符串的所有目录和子目录。现在我有以下代码,其中显示了所有目录和子目录(没有实现字符串模式,这就是我想要的): 如何指定在目录/子目录名称中搜索名称模式 例如,如果我有以下目录结构: 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\
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库:
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写过了。如果您对此代码有任何疑问,请随时提问。递归调用只是为了易于实现,尽管我认为在这种情况下,将此函数重新实现为非递归应该不难。
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