Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Recursivly check files inside folders

Posted on 2007-03-22
14
Medium Priority
?
227 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
The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

 
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 680 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 360 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

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
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 …
Suggested Courses

704 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