java - Efficently find files in specific directories -


i have simple problem: iterate large , nested directory structure using files.walkfiletree this:

final int cutoff = 5; final list<path> foundlist = new arraylist<>(); files.walkfiletree( coderoot, new simplefilevisitor<path>() {     @override     public filevisitresult previsitdirectory(path dir, basicfileattributes attrs)              throws ioexception {         string rpath = coderoot.relativize( dir ).tostring();         int level = rpath.length() - rpath.replace("/", "").length();         if (dir.getfilename().tostring().equals( "target" ) || level < cutoff) {             return filevisitresult.continue;         }         return filevisitresult.skip_subtree;     }     @override     public filevisitresult visitfile( path file, basicfileattributes attrs )              throws ioexception {         if (file.getfilename().tostring().endswith( ".txt" )) {             foundlist.add( file );         }         return filevisitresult.continue;     } } ); 

my goal add files under specific directory target know @ cutoff levels under coderoot.

i'm looking more efficient way in terms of necessary stat() calls or saying "can't done".

language level java8.

the algorithm presented one-time query. in case, you're stuck linear-time search through directories. can't minimize away need examine each directory way. can @ caching, of course, if you're going bother cache coherency , need high performance might consider building index. in either case i'll address question asked, one-time query.

the version of files.walkfiletree you're using walks entire tree, including files , directories past maximum level. you're explicitly excluding them parsing path name, technique rightly think might not efficient. solution read documentation. there's second version of files.walkfiletree maximum depth explicit argument. tutorial on walking file tree:

the second walkfiletree method enables additionally specify limit on number of levels visited , set of filevisitoption enums.

if use second method you'll visit candidate files within maximum level, , can avoid code prunes subtrees.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -