Renaming a folder name which has sub directories i

2019-08-25 07:33发布

问题:

My folder structure is

D:
  root
       popcorn-folder     <--- renaming doesnt work
             popcorn-subfolder   <--- renaming doesnt work
             popcorn-file         <--- renaming doesnt work
       popcorn-folder2       <- renaming works
             popcorn-file1    <--- renaming work

The code is

 public static void renameDirectory(File base) throws IOException{
    //LinkedList<File> fileList = new LinkedList<File>();

    int count=0;//count the renamed files in this directory + its sub. You wanted to do this?

    //Process each file in this folder.
    for (File file: base.listFiles()){

        /*get the name of the file*/
        String origName = file.getName();
        /*get the path of the directory*/
        String baseLoc = file.getParent();

        System.out.println("baseLoc-> "+file.getAbsolutePath());

        File resultFile=file;

        if (origName.contains("popcorn-")  /*|| origName.contains("#") || origName.contains("@")*/){

            System.out.println("Orig name-> "+origName);
            /*origName = origName.replaceAll("&", "_and_");
            origName = origName.replaceAll("@", "_at_");*/

            String newName = origName.replaceAll("POPCORN.", "");
            System.out.println("New Name-> "+newName);
            String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
            System.out.println("newLoc-> "+newLoc);
            File newFile = new File(newLoc);

            System.out.println("renamed file-> "+file.renameTo(newFile));

            count++;
            resultFile=newFile;//not sure if you could do file=newFile, tired
            System.out.println("end");
            System.out.println(resultFile.getAbsolutePath());

        }

        //if this 'file' in the base folder is a directory, process the directory 
        if(resultFile.isDirectory()){//or similar function
            System.out.println("into dir mode");
            renameDirectory(resultFile);
        }
    }

The above code works fine if there is no popcorn-subfolder if the subfolder is there the renaming function returns false. How to solve this? I need to recursively rename no matter file or directories