Solved

iterate through a directory structure

Posted on 2004-04-06
6
4,348 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
fibonacci ten numbers 4 54
login form jsp example 2 56
maven disable workspace resolution 1 43
Java Inheritance super keyword use 8 41
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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:

696 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