使用java File.rename.to()重命名具有子目录的文件夹名称不起作用

时间:2018-01-17 12:12:59

标签: java file-rename

我的文件夹结构是

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

代码是

 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);
        }
    }

如果没有爆米花 - 子文件夹,上面的代码工作正常 如果子文件夹在那里,重命名函数返回false。怎么解决这个?  我需要递归重命名无论文件或目录

0 个答案:

没有答案