recursive folder reading with java.io.File

大憨熊 提交于 2021-01-28 17:47:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!