Skip to main content

Build a Safe Batch File Renaming Tool in Java

· One min read
Apache Wangye
Software developer and technical writer

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

For production code, use java.nio.file.Files.move so failures produce useful exceptions:

Files.move(source.toPath(), target.toPath());

Before applying changes:

  1. Build the complete source-to-target mapping.
  2. Reject duplicate target paths and existing files.
  3. Print or export a preview.
  4. Store a reverse mapping for rollback.
  5. Apply moves only after validation succeeds.

Also decide explicitly whether symbolic links, hidden files, directories, and recursive traversal are allowed.

Page views: --

Total views -- · Visitors --