Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

iterate through a directory structure

Posted on 2004-04-06
6
Medium Priority
?
4,355 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 800 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 600 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 600 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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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:
Suggested Courses

604 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