Solved

Recursivly check files inside folders

Posted on 2007-03-22
14
224 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
[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
  • 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

626 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