java - Retaining the stack position of a recursive function between calls -


this question general, feel best explained specific example. let's have directory many nested sub directories , in of sub directories there text files ending ".txt". sample structure be:

dir1     dir2         file1.txt     dir3         file2.txt     file3.txt 

i'd interested if there way in java build method called return successive text files:

textcrawler crawler = new textcrawler(new file("dir1")); file textfile; textfile = crawler.nextfile(); // value file1.txt textfile = crawler.nextfile(); // value file2.txt textfile = crawler.nextfile(); // value file3.txt 

here challenge: no internal list of text files can saved in crawler object. trivial. in case you'd build initialization method recursively builds list of files.

is there general way of pausing recursive method when called again returns specific point in stack left? or have write specific each situation , solutions have vary file crawlers, org chart searches, recursive prime finders, etc.?

if want solution works on recursive function, can accept consumer object. may this:

public void recursivemethod(consumer<treenode> func, treenode node){   if(node.isleafnode()){       func.accept(node);   } else{     //perform recursive call   } } 

for bunch of files, might this:

public void recursivemethod(consumer<file> func, file curfile){   if(curfile.isfile()){       func.accept(curfile);   } else{     for(file f : curfile.listfiles()){       recursivemethod(func, f);     }   } } 

you can call with:

file startingfile; //initialize f pointing directory recursivemethod((file file)->{   //do file }, startingfile); 

adapt necessary.


Comments