Solved

Recursivly check files inside folders

Posted on 2007-03-22
14
220 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
backtracking recursion  code 19 54
difference of if loops 23 43
expectj telnet failing 5 26
hibernate example for saving data 19 14
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…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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:
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 …

863 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

26 Experts available now in Live!

Get 1:1 Help Now