Solved

iterate through a directory structure

Posted on 2004-04-06
6
4,344 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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse package explorer vs project explorer view 2 133
Java DateChooser? 3 36
egit plugin on eclipse 8 63
tomcat not starting 6 45
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

777 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