问题
Currently I create a list of sub folders with this function:
% create list of all sub folders
dirs = regexp(genpath(basePath),['[^;]*'],'match');
My folders contain however > 100 000 files. This function takes minutes to hours to complete. The number of folders however is only < 100.
I read that java.io.File
is magnitudes faster. However how can I use it to read folders recursive?
jFile = java.io.File([basePath '*']); %java file object
jPaths = jFile.listFiles; %java.io.File objects
jNames = jFile.list; %java.lang.String objects
isFolder = arrayfun(@isDirectory,jPaths); %boolean
dirs = cellstr(char(jNames(~isFolder))); %cellstr
gives me an empty array back.
EDIT: I tried the following, but the recursion fails because the dirs array is empty after the functions comes back - as if the dirs was a global variable...
function [sub] = subfolders (CurrPath,sub)
%------------------------------------------------
jFile = java.io.File(CurrPath); %java file object
jPaths = jFile.listFiles; %java.io.File objects
jNames = jFile.list; %java.lang.String objects
isFolder = arrayfun(@isDirectory,jPaths); %boolean
dirs = cellstr(char(jNames(isFolder))) %cellstr
if nargin == 1
sub = {};
end
for i = 1:numel(dirs)
currSubDir = dirs{i};
if ~isempty(currSubDir)
sub{end+1} = fixPath([CurrPath '\' currSubDir]);
sub = subfolders(sub{end},sub);
end
end% if
来源:https://stackoverflow.com/questions/26776523/recursive-folder-reading-with-java-io-file