Build a Safe Batch File Renaming Tool in Java
· One min read
Batch renaming is less about speed than preventing overwrites and irreversible mistakes. A reliable tool should first generate a preview, detect duplicate target names and invalid paths, and require confirmation before changing files.
The following example appends .json to filenames made of six digits:
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String directory = "C:\\tests";
String matchRegex = "(\\d{6})";
String replaceRegex = "$1.json";
Pattern pattern = Pattern.compile(matchRegex);
File folder = new File(directory);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
System.out.println("files: " + files.length);
for (File source : files) {
Matcher matcher = pattern.matcher(source.getName());
if (!matcher.matches()) {
continue;
}
String targetName = matcher.replaceAll(replaceRegex);
File target = new File(source.getParentFile(), targetName);
System.out.printf("%s -> %s%n", source.getName(), targetName);
if (target.exists()) {
System.err.println("Skipped because the target already exists: " + target);
continue;
}
if (!source.renameTo(target)) {
System.err.println("Rename failed: " + source);
}
}
}
}
Recommended improvements
For production code, use java.nio.file.Files.move so failures produce useful exceptions:
Files.move(source.toPath(), target.toPath());
Before applying changes:
- Build the complete source-to-target mapping.
- Reject duplicate target paths and existing files.
- Print or export a preview.
- Store a reverse mapping for rollback.
- Apply moves only after validation succeeds.
Also decide explicitly whether symbolic links, hidden files, directories, and recursive traversal are allowed.