Solved

Recursivly check files inside folders

Posted on 2007-03-22
14
221 Views
Last Modified: 2010-03-31
Given a path to a directory the following code is used for renaming the files(insdie that directory) based on certain condition

public void changeImageName(String sourcePath) {

            Pattern p = Pattern.compile("[a-zA-Z1-90_\\- \\.]*");

            File filePath = new File(sourcePath);

            File[] listFiles = filePath.listFiles();
            for (int i = 0; i < listFiles.length; i++) {

                  Matcher m = p.matcher(listFiles[i].getName());
                  boolean b = m.matches();

                  if (!b) {
                        logger.debug(" File Name is: " + listFiles[i].getName()
                                    + " Status: " + b);

                        String newFileName = listFiles[i].getName().replaceAll(
                                    "[^a-zA-Z \\.0-9_-]", "_");
                        logger.debug("New File Name:  " + newFileName);

                        boolean renameSuccess = listFiles[i].renameTo(new File(
                                    listFiles[i].getParentFile(), newFileName));

                        if (renameSuccess) {
                              logger.debug("Rename of file: " + listFiles[i].getName()
                                          + " to: " + newFileName + " succeded\n");
                        } else {
                              logger.debug(" Rename of file: " + listFiles[i].getName()
                                          + " to: " + newFileName + " FAILED\n");
                        }
                  }
            }
      }

The files which need to be renamed are renamed and rest of them are left as they are.

If the folder path passed is C:\img then the files inside this folder are checked and renamed as per the condition.
But if the files are inside a folder which is inside the img folder then they are not checked.
Say, if the path passed is C:\img and there is a folder high inside C:\img then this folder will not be checked. Is there a way to make this program work recursivly.
Please help
0
Comment
Question by:russell_2463
  • 5
  • 5
  • 4
14 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 18769608
See

http://www.exampledepot.com/egs/java.io/TraverseTree.html

Put the above processing in a method call 'process'
0
 
LVL 92

Expert Comment

by:objects
ID: 18769705
add the following to also process directories

            for (int i = 0; i < listFiles.length; i++) {
            if (listFiles[i].isDirectory()) {
                 changeImageName(listFile[i].getAbsolutePath())
            } else {
                 Matcher m = p.matcher(listFiles[i].getName());
                 ...
0
 

Author Comment

by:russell_2463
ID: 18769816
>>Put the above processing in a method call 'process'

Should I put my code in the method called process?
0
Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
LVL 86

Expert Comment

by:CEHJ
ID: 18769836
Yes. It's cleaner to separate file recursion code from the key functionality
0
 

Author Comment

by:russell_2463
ID: 18769859
So does that mean whereever the process method is called I should call changeImageName() method. But there is a concern here:
1. The changeImageName() method is getting directly called from the main() method. Now which method should be called from the main() method.
2. Also changeImageName(String) accepts a String arg as path of directory, whereas process(File) accepts a File object.
0
 

Author Comment

by:russell_2463
ID: 18769873
>>Also changeImageName(String) accepts a String arg as path of directory, whereas process(File) accepts a File object.

May be this'll solve the 2nd problem
public void changeImageName(File sourcePath) {

            Pattern p = Pattern.compile("[a-zA-Z1-90_\\- \\.]*");

            File filePath = new File(sourcePath.getAbsolutePath());
0
 

Author Comment

by:russell_2463
ID: 18769891
but how to solve the problem no. 1
0
 

Author Comment

by:russell_2463
ID: 18769935

Here is the whole code now. When will the recursive functions be called?


public static void main(String[] args) {

                  String sourcePath = args[0];
                  changeImageName(new File(sourcePath));

      }

public static void changeImageName(File sourcePath) {

            Pattern p = Pattern.compile("[a-zA-Z1-90_\\- \\.]*");

            File filePath = new File(sourcePath.getAbsolutePath());

            File[] listFiles = filePath.listFiles();
            for (int i = 0; i < listFiles.length; i++) {
              if (listFiles[i].isDirectory()) {
                       changeImageName(listFiles[i]);
            } else {
                   Matcher m = p.matcher(listFiles[i].getName());
                   boolean b = m.matches();

                    if (!b) {
                        logger.debug("File Name is: " + listFiles[i].getName()
                                          + " Status: " + b);
      
                        String newFileName = listFiles[i].getName().replaceAll(
                                          "[^a-zA-Z \\.0-9_-]", "_");
                        logger.debug("New File Name:  " + newFileName);
      
                        boolean renameSuccess = listFiles[i].renameTo(new File(
                                          listFiles[i].getParentFile(), newFileName));
      
                        if (renameSuccess) {
                                    logger.debug("Rename of file: " + listFiles[i].getName()
                                                + " to: " + newFileName + " succeded\n");
                        } else {
                                    logger.debug("Rename of file: " + listFiles[i].getName()
                                                + " to: " + newFileName + " FAILED\n");
                        }
                  } else {
                              logger.debug("File Name is: " + listFiles[i].getName()
                                          + " not required to be renamed ");
                        }
               }
            }
      }      // Process all files and directories under dir
      public static void visitAllDirsAndFiles(File dir) {
            changeImageName(dir);

            if (dir.isDirectory()) {
                  String[] children = dir.list();
                  for (int i = 0; i < children.length; i++) {
                        visitAllDirsAndFiles(new File(dir, children[i]));
                  }
            }
      }

      // Process only directories under dir
      public static void visitAllDirs(File dir) {
            if (dir.isDirectory()) {
                  changeImageName(dir);

                  String[] children = dir.list();
                  for (int i = 0; i < children.length; i++) {
                        visitAllDirs(new File(dir, children[i]));
                  }
            }
      }

      // Process only files under dir
      public static void visitAllFiles(File dir) {
            if (dir.isDirectory()) {
                  String[] children = dir.list();
                  for (int i = 0; i < children.length; i++) {
                        visitAllFiles(new File(dir, children[i]));
                  }
            } else {
                  changeImageName(dir);
            }
      }
0
 
LVL 92

Expert Comment

by:objects
ID: 18769938
you don't need all that extra stuff
all u need is what I first posted.
0
 
LVL 92

Accepted Solution

by:
objects earned 170 total points
ID: 18769948
the recursive call is already there

              if (listFiles[i].isDirectory()) {
                       changeImageName(listFiles[i]);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18769952
You only need

public static void visitAllFiles(File dir)
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 90 total points
ID: 18769961
process would be

      public void process(File file) {
          changeImageName(file.getAsbolutePath());
      }
0
 
LVL 92

Expert Comment

by:objects
ID: 18770082
>      public void process(File file) {
>          changeImageName(file.getAsbolutePath());
>      }

u don't need/want that :)
your code already does the job without having to add extra complexity that serves no purpose
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18770241
:-)

Beware of coupling your application code with system code. Your code should be called as per the example i gave you. In fact it should really be even more loosely coupled used the Observer pattern
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

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…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This video teaches viewers about errors in exception handling.

821 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