Solved

iterate through a directory structure

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 82
strCopies  challenge 17 73
@SBGen Method 3 25
Impossible to extract MSI from new JAVA releases 2 38
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

707 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now