Sunday, August 30, 2015

How to Batch-Rename all files in a directory using Java

An example of how to rename all files in a directory.  This works by copying the files to a destination directory. Make sure the destination directory exists first.


package au.com.vectorams.stormtomdmreceivedata.unit;

import java.io.File;

import org.apache.commons.io.FileUtils;

/**
 * Utility to copy all files in a source directory to a target directory,
 * optionally renaming them.
 */
public class BatchRename {

       /**
        * Use regular expressions or simple string conversions to convert the
        * source file name to the destination file name. In this example keep
        * everything after the first two underscores in the source file name.
        *
        * @param name
        *            the source file name
        * @return the destination file name
        */
       private static String convertFileName(String name) {
             String newName = name.substring(name.indexOf('_') + 1);
             newName = newName.substring(newName.indexOf('_') + 1);
             return newName;
       }

       public static void main(String... args) throws Exception {

             String srcDirPath = "C:/temp/MY_FILES/";
             String destDirPath = "C:/temp/MY_FILES_renamed/";

             File srcDir = new File(srcDirPath);

             File[] srcFiles = srcDir.listFiles();

             for (int i = 0; i < srcFiles.length; i++) {
                    File src = srcFiles[i];

                    if (src.isFile()) {

                           File dest = new File(destDirPath + convertFileName(src.getName()));

                           System.out.println("copying " + src + " to " + dest);

                           FileUtils.copyFile(src, dest, true);
                    }
             }
       }

}