0

How would you iterate through a filesystem tree given a node which is essentially the root node? Since it is iteration, the only two methods which I have to define are hasNext() and next(). I know that I have to use listFiles(), isDirectory(), and exists(), but I am unsure of how to implement them. I DON'T want any code, but I would just like someone to maybe give me some insight as to how I would go about doing hasNext() or next(). Thanks again for any help!

dzagnyr
  • 33
  • 6
  • You might look at Guava's [fileTreeTraverser](http://docs.guava-libraries.googlecode.com/git/javadoc/src-html/com/google/common/io/Files.html#line.803), which provides various tree iterators [here](http://docs.guava-libraries.googlecode.com/git/javadoc/src-html/com/google/common/collect/TreeTraverser.html#line.54). – Louis Wasserman Mar 26 '15 at 02:05
  • Take a look at http://stackoverflow.com/a/6006609/2891664 (use a stack or list). – Radiodef Mar 26 '15 at 02:12

2 Answers2

0

well at first you could define a function like

listrecursive(Element e) 

which receives an element. if this element is a directory, you invoke the listrecurisive function for each of the elements within this directory. of course to loop over all elements you can use an iterator, i.e.

function listrecursive(Element e){
if(e isDirectory){
   Iterator iter = e.iterator();
       while(iter.hasNext()){
          Element ie = iter.next();
          listRecursive(ie);  
    }
}
else{
 //process file
}
}

Sry but i had to include some code... at least it will not run, I promise ;-)

Ueli Hofstetter
  • 2,409
  • 4
  • 29
  • 52
0

I guess recursion would be the best match :

private void getDirectoryStructure(String rootNode) {
    List<String> fileList = new LinkedList<String>();
    getSubDirectories(new File(rootNode), fileList);
    // fileList got the data you need
}

public static void getSubDirectories(File rootNode, List<String> fileList){
    if(rootNode.isDirectory()){
        fileList.add(rootNode.getAbsolutePath());
        File[] subDirectory = rootNode.listFiles();
        for(File sub : subDirectory){
            getSubDirectories(sub, fileList);
        }
    }
}
Kartic
  • 2,935
  • 5
  • 22
  • 43