Solved

iterate through a directory structure

Posted on 2004-04-06
6
4,346 Views
Last Modified: 2008-02-26
dear java experts,
                        Can somebody help me decipher the logic to write a method to iterate through a directory structure and look for only xml files.the structure i am looking to parse is like this

root
  a
     a.1
         xyz.xml
     a.2
         a.2.1
            hhh.xml
 b
    b.1
        ttt.xml

i have written a preliminary function like this

xml dir here is the root dir

protected void iterateFilesInDirectory(String xmldir){
            File dir = new File(xmldir);
            File [] files = dir.listFiles();
            count =0
            if (files!=null)
                 {
               for (int idx=0;idx<files.length;idx++)
               {
                if(files[idx].isDirectory() == false) {
                String originalfileName=files[idx].getName();
                if( originalfileName.endsWith("xml") ) {                        
                    originalXmlFile = files[idx];
                   count = count+1;
                }
                }else{
                iterateFilesInDirectory(files[idx].getName())
                }
              }
              }

       }




0
Comment
Question by:Testsubbu
6 Comments
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 10766027
You need to recurse. Here's a class that you can use:

      class FileFinder {
            private File fileFound = null;
            private boolean caseInsensitiveSearch;


            /**
             *  Do we want to search without case sensitivity?
             *
             * @param  caseInsensitiveSearch  Whether case-insensitive
             */
            public void setCaseInsensitiveSearch(boolean caseInsensitiveSearch) {
                  this.caseInsensitiveSearch = caseInsensitiveSearch;
            }


            /**
             *  Gets whether we want to search without case sensitivity?
             *
             * @return    The caseInsensitiveSearch value
             */
            public boolean getCaseInsensitiveSearch() {
                  return caseInsensitiveSearch;
            }


            /**
             *  Description of the Method
             *
             * @param  collector          Description of the Parameter
             * @param  extension          Description of the Parameter
             * @param  f                  Description of the Parameter
             */
            public final void findFilesByExtension(File f, java.util.List collector, String extension) {
                  if (f.getName().endsWith(extension)) {
                        collector.add(f);
                  }
                  File[] children = f.listFiles();
                  for (int i = 0; ((fileFound == null) && children != null) && (i < children.length); i++) {
                        if (children[i].isDirectory()) {
                              // Recurse subdirectories
                              findFilesByExtension(children[i], collector, extension);
                        }
                        // Ensure that it's a 'real' file
                        else if (children[i].isFile()) {
                              if (children[i].getName().endsWith(extension)) {
                                    collector.add(f);
                              }
                        }
                        //end else
                  }
                  //end for

            }


            /**
             *  Description of the Method
             *
             * @param  f     A starting directory
             * @param  name  The name of the file to find
             * @return       A reference to the file if found, else null
             */
            public final File findFile(File f, String name) {
                  if (f.getName().equals(name)) {
                        fileFound = f;
                        return fileFound;
                  }
                  File[] children = f.listFiles();
                  for (int i = 0; ((fileFound == null) && children != null) && (i < children.length); i++) {
                        if (children[i].isDirectory()) {
                              // Recurse subdirectories
                              findFile(children[i], name);
                        }
                        // Ensure that it's a 'real' file
                        else if (children[i].isFile()) {
                              if (children[i].getName().equals(name)) {
                                    fileFound = children[i];
                                    break;
                              }
                        }
                        //end else
                  }
                  //end for
                  return fileFound;
            }
      }

}
0
 
LVL 14

Assisted Solution

by:Tommy Braas
Tommy Braas earned 150 total points
ID: 10766055
I would suggest that you use the File.list() method instead of listFiles as you're not using the File objects you create for anything but to get the name of the files. File.list() returns an array of filenames in a directory. You would have to build up the path as you send it through the recursion.

Try this to solve your problem:
dir.listFiles(new FilenameFilter() {
   boolean accept(File dir, String name) {
      return name.endsWith(".xml");
   }
});

By implementing the above code, you can simplify your logic a lot.
0
 
LVL 92

Accepted Solution

by:
objects earned 150 total points
ID: 10770699


public List getFile(File dir, FileFilter filter)
{
    if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory");
    return handleDirectory(new ArrayList(), dir, filter);
}


private handleDirectory(List result, FileFilter filter, File f)
{
    File[] files = f.listFiles();
    for (int i=0; i<files.length; i++)
    {
       if (files[i].isDirectory())
       {
          handleDirectory(result, filter, files[i]);
       }
       else if (filter.accept(files[i]))
       {
          result.add(files[i]);
       }
    }
}

statci class XMLFileFilter implements FileFilter
{
   public boolean accept(File f)
   {
      return f.getName().toLowerCase().endsWith(".xml");
   }
}
0
 
LVL 9

Expert Comment

by:doronb
ID: 10776528
objects,

I think your getFile(..) method should look like this:

public List getFile(File dir, FileFilter filter) {
    if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory");
    arrayList = new ArrayList();
    handleDirectory(arrayList, dir, filter);
    return arrayList;
}
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 10964064
Three-way point split
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

838 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question