Solved

Recursivly check files inside folders

Posted on 2007-03-22
14
219 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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

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…
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…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

762 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