SoFunction
Updated on 2025-04-14

Writing a file batch renaming tool in Java

background

When developing mobile applications, UI designs usually provide image resources at different resolutions to adapt to multiple screen sizes. For example, in a specific application scenario, the seekbar range 0-64 corresponds to 64 pictures, which are used to slide to switch different color backgrounds. The designer provides a collection of three different sizes of picture: "xhdpi", "xxhdpi", and "xxxhdpi", with a total of 192 pictures. Manually prefixing or performing other formatting operations to these images is time-consuming and error-prone. Therefore, in order to improve efficiency and reduce human errors, a Java tool class is written hereFileRenamer, to automate this process.

deal with

1. Folder inspection and traversal

first,FileRenamerThe class defines the prefix and source folder path for the new file name. Then passrename()Method gets the folder object under the specified path and verifys its validity. Next, it traverses the preset subfolders (such as "xhdpi", "xxhdpi", "xxxhdpi") and calls each existing subfolderprocessSubFolder()The method is further processed.

2. Batch renaming

existprocessSubFolder()In the method, the program filters out all.pngfile and use regular expressions to match numbers and color values ​​in filenames. Construct a new file name based on the matching result, retain the original numeric part, and change the file name to a form with a specified prefix, such as0_color_ffff00.pngarriveic_wangyou_color0_ffffff.png. After successful renaming, the program will output confirmation information; if it fails, an error will be recorded.

3. Output configuration code snippet

at last,outputCodeSnippet()The method is responsible for generating a piece of code that can be copied and pasted into the project configuration. This method first filters and sorts all PNG files that meet the new prefix, and then constructs a string containing references to these files. In addition, it lists files that are not included so that the developer can check for any omissions.

Complete code

Through the above steps,FileRenamerThe function of batch renaming image files is realized and configuration code snippets are automatically generated, greatly simplifying the workload of resource management. The following is the complete source code of this tool class:

package ;

import ;
import ;
import ;
import ;
import ;
import ;

public class FileRenamer {

    private static final String NEW_PREFIX = "ic_wangyou_color";
    private static final String FOLDER_PATH = "/storage/emulated/0/wangyou";

    public static void rename() {
        File folder = new File(FOLDER_PATH);
        if (!() || !()) {
            ("The specified path is not a valid folder!");
            return;
        }

        String[] subFolders = {"xhdpi", "xxhdpi", "xxxhdpi"};

        for (String subFolderName : subFolders) {
            File subFolder = new File(folder, subFolderName);
            if (() && ()) {
                processSubFolder(subFolder);
            } else {
                ("Subfolder" + subFolderName + "Not exists or is not a valid folder!");
            }
        }
    }

    private static void processSubFolder(File subFolder) {
        File[] files = ((dir, name) -> ().endsWith(".png"));
        if (files == null ||  == 0) {
            ("In folder" + () + "No .png files were found in!");
            return;
        }

        for (File oldFile : files) {
            String oldFileName = ();
            Pattern pattern = ("(\\d+)_(\\w+\\.png)");
            Matcher matcher = (oldFileName);

            if (()) {
                String numberPart = (1);
                String colorValueWithExt = (2);
                String colorValue = ("\\.")[0];

                String newFileName = NEW_PREFIX + numberPart + "_" + colorValue + ".png";
                File newFile = new File(subFolder, newFileName);

                if ((newFile)) {
                    ("Renamed: " + oldFileName + " -> " + newFileName);
                } else {
                    ("Failed to rename: " + oldFileName);
                }
            } else {
                ("Invalid file name format: " + oldFileName);
            }
        }

        outputCodeSnippet(subFolder);
    }

    private static void outputCodeSnippet(File folder) {
        Pattern pattern = ("(?<=color)(\\d+)(?=_)");

        List<File> allPngFiles = (())
                .filter(file -> ().toLowerCase().endsWith(".png"))
                .collect(());

        List<File> renamedFiles = ()
                .filter(file -> ().startsWith(NEW_PREFIX))
                .sorted((f1, f2) -> {
                    Matcher m1 = (());
                    Matcher m2 = (());
                    if (() && ()) {
                        return ((()), (()));
                    }
                    return 0;
                })
                .collect(());

        ("Prepare to output string renamedFiles: " + ());

        StringBuilder outputString = new StringBuilder("private final int[] wangyou_colorArr_" + () + " = new int[]{\n");

        for (File file : renamedFiles) {
            String fileNameWithoutExtension = ().replaceFirst("[.][^.]+$", "");
            ("            .")
                    .append(fileNameWithoutExtension)
                    .append(",\n");
        }

        if (().endsWith(",\n")) {
            (() - 2);
        }
        ("\n};");

        (());

        List<File> unmatchedFiles = ()
                .filter(file -> !().startsWith(NEW_PREFIX))
                .collect(());

        if (!()) {
            ("The following file is not included:");
            (file -> ("    " + ()));
        }
    }
}

This code not only solves the problem of renaming large batches of image files, but also automatically generates corresponding resource arrays, making it easy to integrate these resources in the project. This is just an example. Of course, the actual use must be processed according to different file names, so copying is definitely not possible.

This is the end of this article about using Java to write a file batch renaming tool. For more related content on batch renaming of Java files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!