Batch File Renaming with Java

Below is an example of how Microsoft Excel files can be renamed in a batch, based on the contents of a particular cell within each file. For this to work the dependencies Apache POI and Apache Commons must be used.

Firstly, the file path is set and a check is carried out to make sure that the path exists. This is followed by a check to make sure that there are files to process at the desired location. Each file is then processed one by one. All files without a ‘.xlsx’ extension are ignored. If the value in the specified cell of the first sheet in each individual file is populated and it contains only valid characters then the file is renamed and a message is displayed confirming each name change, otherwise a message is displayed stating that a particular file name could not been changed. Finally, a count of the number of files that have been renamed is displayed.

import java.io.File;
import java.io.FileInputStream;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
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 BatchFileRenaming {

    public static void main(String[] args) {

        // File path.
        File path = new File("c:/demo");

        // Renamed file.
        File newFile;

        // Check to see if the file path exists.
        if (path.isDirectory()) {

            // Check if there are any files at the path.
            File [] files = path.listFiles();
            String fileExtension;

            if (files.length == 0) {

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

            } else {

                // Excel file variables.
                FileInputStream fis;
                XSSFWorkbook workbook;
                XSSFSheet sheet;
                XSSFRow row;
                XSSFCell cell;
                String newFileName;

                // Renamed file count.
                int filesRenamed = 0;

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

                // Process the files at the path.
                for (File file : files) {

                    // Check if the item is a file.
                    if (file.isFile()) {

                        // Extract the file extension from the name.
                        fileExtension = FilenameUtils.getExtension(file.getName());

                        // Check if the file is an Excel file, excluding temp files.
                        if (fileExtension.contains("xlsx") &&
                                !file.getName().contains("~")) {

                            try {

                                // Open the Excel file.
                                fis = new FileInputStream(file);
                                workbook = new XSSFWorkbook(fis);

                                // First sheet from workbook.
                                sheet = workbook.getSheetAt(0);

                                // Cell containing new file name, equivalent to cell A1.
                                row = sheet.getRow(0);
                                cell = row.getCell(0);

                                // Construct the new file path and name.
                                newFileName = path + "\\" + cell.getStringCellValue()
                                        + ".xlsx";
                                newFile = new File(newFileName);

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

                                    // Rename the file.
                                    if (file.renameTo(newFile)) {

                                         // Renamed file message.
                                         System.out.printf("The file \"%s\" has been " +
                                                 "renamed to \"%s\".\n", file.getName(),
                                                 newFile.getName());

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

                                    } else {

                                         System.out.printf("The file \"%s\" could not " +
                                                         "be renamed.\n", file.getName());

                                     }

                                } else {

                                    System.out.printf("The file \"%s\" could not be " +
                                                    "renamed.\n", file.getName());

                                }

                                // Close the Excel file.
                                workbook.close();
                                fis.close();

                            } catch (Exception e){

                                // Display a message where files could not be renamed.
                                System.out.printf("The file \"%s\" could not be " +
                                                "renamed.\n", file.getName());

                            }

                        }

                    }

                }

                // Message stating the number of files renamed.
                if (filesRenamed == 0) {
                    System.out.println("No files have been renamed.");
                } else if (filesRenamed == 1) {
                    System.out.printf("%s file has been renamed.", filesRenamed);
                } else {
                    System.out.printf("%s files have been renamed.", filesRenamed);
                }

            }

        } else {

            // Display a message stating file path does not exist.
            System.out.println("File path does not exist.");

        }

    }

}