Renaming a folder name which has sub directories is not working using java File.rename.to()

一世执手 提交于 2020-01-06 06:40:31

问题


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

来源:https://stackoverflow.com/questions/48300897/renaming-a-folder-name-which-has-sub-directories-is-not-working-using-java-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!