Batch File Search and Renaming with Java

If it is necessary to rename a batch of files, where both the existing and new file names exist in an Excel spreadsheet, Java can be used to automate the renaming process.

In the example below, a spreadsheet called “Documents to rename.xlsx” contains the file name information. Column ‘A’ contains the existing file name, without the file extension, column ‘B’ contains the new file name, if available, without the extension, and column ‘C’ is for notes to be added during the renaming process.

Existing File Name New File Name Notes
OldFileName1 NewFileName1
OldFileName2
OldFileName3 NewFileName3
OldFileName4 NewFileName4

First of all, the path to the above document, as well as to the files to be renamed, is set, along with other variables, and a check is made to see if they exist. If they do exist, the document containing the file names is opened and the file name information on the first sheet is processed. The last row used is obtained and all the rows, from the second to the last are handled one by one. The current and new file names are extracted from columns ‘A’ and ‘B’, using their numerical references, 0 and 1. A check is made to see if the file exists with the current name and if it does the file gets renamed to the new name, providing there is one available. Feedback is added in column ‘C’ as to whether the file was renamed or not, or, if it had already been renamed. Overall feedback is also given as to the total number of files renamed.

For this to work the dependencies Apache POI and Apache Commons must be used.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;

public class BatchFileSearchRename {

    public static void main(String[] args) {

        // File names workbook.
        FileInputStream fisNamesDoc = null;
        File pathNamesDoc = new File("C:/Demo/Rename/Documents to rename.xlsx");
        XSSFWorkbook xlNamesWorkbook = null;
        XSSFSheet xlNamesWorksheet;
        XSSFRow xlNamesRow;
        XSSFCell xlNamesCellCurrent;
        XSSFCell xlNamesCellNew;
        XSSFCell xlNamesCellNotes;

        // Last row and file variables.
        long lastRow;
        File currentFileName = null;
        File newFileName = null;
        String fileExtension = ".docx";

        // File name regular expression.
        Pattern pattern = Pattern.compile(
            "# Match a valid Windows filename (unspecified file system).         \n" +
            "^                                # Anchor to start of string.       \n" +
            "(?!                              # Assert filename is not: CON, PRN,\n" +
            "  (?:                            # AUX, NUL, COM1, COM2, COM3, COM4,\n" +
            "    CON|PRN|AUX|NUL|             # COM5, COM6, COM7, COM8, COM9,    \n" +
            "    COM[1-9]|LPT[1-9]            # LPT1, LPT2, LPT3, LPT4, LPT5,    \n" +
            "  )                              # LPT6, LPT7, LPT8, and LPT9...    \n" +
            "  (?:\\.[^.]*)?                  # followed by optional extension   \n" +
            "  $                              # and end of string                \n" +
            ")                                # End negative lookahead assertion.\n" +
            "[^<>:\"/\\\\|?*\\x00-\\x1F]*     # 0 or more valid filename chars.  \n" +
            "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .]  # Last char is not a space or dot. \n" +
            "$                                # Anchor to end of string.            ",
            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);

        // Renamed file count.
        int filesRenamed = 0;

        // Path to documents to rename.
        File pathDocsRename = new File("C:/Demo");

        // Check if the file and folder paths exist.
        if (pathNamesDoc.isFile() && pathDocsRename.isDirectory()) {

            try {

                // Open the file names workbook and assign to a variable.
                fisNamesDoc = new FileInputStream(pathNamesDoc);
                xlNamesWorkbook = new XSSFWorkbook(fisNamesDoc);

            } catch (Exception e) {

                // Message stating that workbook can't be opened.
                System.out.println("Unable to open file names workbook.");

                // Stop program execution.
                System.exit(0);

            }

            // Select the first sheet.
            xlNamesWorksheet = xlNamesWorkbook.getSheetAt(0);

            // Find the last row used.
            // Row numbering starts at zero.
            lastRow = xlNamesWorksheet.getLastRowNum();

            // Check if there are any files to rename.
            if (lastRow <= 1) {

                // Message stating no files to rename.
                System.out.println("There are no files to rename.");

            } else {

                // Process the rows, from second row to the last used.
                for (int row = 1; row <= lastRow; row++) {

                    // Extract the current and new file name.
                    xlNamesRow = xlNamesWorksheet.getRow(row);
                    xlNamesCellCurrent = xlNamesRow.getCell(0,
                            Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    xlNamesCellNew = xlNamesRow.getCell(1,
                            Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    xlNamesCellNotes = xlNamesRow.getCell(2,
                            Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

                    // Assign the current file name to a file variable.
                    currentFileName = new File(pathDocsRename + "\\"
                            + xlNamesCellCurrent.toString() + fileExtension);

                    // Construct the new file path and name.
                    newFileName = new File(pathDocsRename + "\\"
                            + xlNamesCellNew.toString() + fileExtension);

                    // Check if the file exists and a new name has been provided.
                    if (currentFileName.isFile() &&
                            !xlNamesCellNew.getStringCellValue().equals("")) {

                        // Check if the new file name is valid.
                        if (pattern.matcher(newFileName.getName()).find()) {

                            // Rename the file.
                            if (currentFileName.renameTo(newFileName)) {

                                // Add message to column C stating file has been renamed.
                                xlNamesCellNotes.setCellValue("File has been renamed.");

                                // Increment the files renamed count.
                                filesRenamed += 1;

                            } else {

                                // Add message to column C stating file can't be renamed.
                                xlNamesCellNotes
                                        .setCellValue("File could not be renamed.");

                            }

                        } else {

                            // Add message in column C stating no new valid name
                            // provided.
                            xlNamesCellNotes
                                    .setCellValue("No new valid file name provided.");

                        }

                    } else {

                        // Check if new file name has been provided.
                        if (xlNamesCellNew.getStringCellValue().equals("")) {

                            // Add message in column C stating no new file name provided.
                            xlNamesCellNotes
                                    .setCellValue("No new valid file name provided.");

                        }
                        // Check if file has already been renamed.
                        else if (newFileName.isFile()) {

                            // Add message in column C stating file already renamed.
                            xlNamesCellNotes
                                    .setCellValue("File has already been renamed.");

                        } else {

                            // Add message in column C stating file does not exist.
                            xlNamesCellNotes
                                    .setCellValue("File does not exist.");

                        }

                    }

                }

                try {

                    // Save the file names workbook.
                    FileOutputStream fosNamesDoc =
                            new FileOutputStream(new File(pathNamesDoc.getPath()));
                    xlNamesWorkbook.write(fosNamesDoc);
                    fosNamesDoc.close();

                } catch (Exception e) {

                    // Message stating file names workbook could not be saved.
                    System.out.println("The file names workbook could not be saved.");

                }

                // Feedback on renamed files.
                if (filesRenamed == 0) {

                    System.out.println("No files were renamed.");

                } else if (filesRenamed == 1) {

                    System.out.printf("%s file renamed successfully.\n", filesRenamed);

                } else {

                    System.out.printf("%s files renamed successfully.\n", filesRenamed);

                }

            }

            try {

                // Close the Excel file.
                fisNamesDoc.close();
                xlNamesWorkbook.close();

            } catch (Exception e) {

                // Message stating file names workbook could not be closed.
                System.out.println("The file names workbook could not be closed.");

            }


        } else {

            // Check if it's the file or folder path that doesn't exist.
            if (!pathNamesDoc.isFile()) {

                // Error message if file names workbook doesn't exist.
                System.out.println("The document containing the file " +
                        "names does not exist.");

            } else {

                // Error if folder path for documents to be renamed doesn't exist.
                System.out.println("The location of the files to rename " +
                        "does not exist.");

            }

        }

    }

}