Java Automation: Rename Hundreds of Files in Seconds

Java Automation: Rename Hundreds of Files in Seconds

Java Automation: Rename Hundreds of Files in Seconds

 

Renaming dozens or even hundreds of files manually is time-consuming and error-prone. Whether you’re organizing thousands of camera photos, web assets, or scanned documents, Java offers a reliable and powerful way to automate batch file renaming. In this post, we’ll explore how to use Java’s File API to rename files based on different patterns like timestamps, incremental counters, or a custom naming convention.

1. Why Use Java for Batch File Renaming?

Java is platform-independent, stable, and has a mature file I/O system, making it a great choice for file automation tasks. With just a few lines of code, you can:

  • List and filter files in a directory
  • Rename files based on specific patterns
  • Handle naming conflicts and exceptions gracefully

This kind of automation can be useful for photographers organizing image folders, developers managing assets, or businesses processing scanned documents at scale.

2. Basic File Renaming with Java

Let’s start with a simple script that renames all .jpg files in a folder by adding a prefix and an incremental counter.

import java.io.File;

public class BasicRenamer {
    public static void main(String[] args) {
        File directory = new File("/path/to/your/images");
        File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg"));

        int count = 1;
        for (File file : files) {
            String newName = String.format("image_%03d.jpg", count++);
            File newFile = new File(directory, newName);
            if (file.renameTo(newFile)) {
                System.out.println("Renamed to: " + newFile.getName());
            } else {
                System.err.println("Failed to rename: " + file.getName());
            }
        }
    }
}

Key takeaways: We filter JPEG files and rename them with a zero-padded counter. This is useful when order matters and uniform naming is desired.

3. Pattern-Based Renaming with Timestamps

Another common need is renaming files based on the last modified timestamp. This helps sort files chronologically and trace original create times.

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampRenamer {
    public static void main(String[] args) {
        File directory = new File("/path/to/your/images");
        File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg"));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");

        for (File file : files) {
            long lastModified = file.lastModified();
            String formattedDate = sdf.format(new Date(lastModified));
            String newName = formattedDate + ".jpg";
            File newFile = new File(directory, newName);
            if (!newFile.exists() && file.renameTo(newFile)) {
                System.out.println("Renamed to: " + newFile.getName());
            } else {
                System.err.println("Failed or duplicate: " + file.getName());
            }
        }
    }
}

This format ensures files are renamed consistently across platforms using their modification time.

4. Avoid Naming Collisions and Maintain Safety

When renaming dozens or hundreds of files, you must check for name collisions. Java’s File.exists() helps avoid overwriting existing files.

String newName = formattedDate + ".jpg";
File newFile = new File(directory, newName);
if (newFile.exists()) {
    newName = formattedDate + "_" + System.currentTimeMillis() + ".jpg";
    newFile = new File(directory, newName);
}

This snippet adds a timestamp-based suffix to avoid duplicates. You could also implement a UUID-based approach for guaranteed uniqueness.

5. Advanced Techniques: Naming by Metadata or Regex

Sometimes images are named inconsistently and include random characters. Here’s how to leverage regex or external metadata for renaming:

import java.io.File;
import java.util.regex.*;

public class RegexRenamer {
    public static void main(String[] args) {
        File dir = new File("/path/to/files");
        File[] files = dir.listFiles((d, name) -> name.endsWith(".jpg"));

        Pattern pattern = Pattern.compile("img_(\\d{4})(\\d{2})(\\d{2})");

        for (File file : files) {
            Matcher matcher = pattern.matcher(file.getName());
            if (matcher.find()) {
                String newName = matcher.group(1) + "-" + matcher.group(2) + "-" + matcher.group(3) + ".jpg";
                File newFile = new File(dir, newName);
                file.renameTo(newFile);
                System.out.println("Renamed to: " + newName);
            }
        }
    }
}

Whether you’re parsing old file names or replacing noisy strings, regex allows powerful transformations for custom renaming logic.

6. Performance Tips for Large Directories

For directories with thousands of files, performance becomes a concern. Consider the following practices:

  • Use Stream APIs to process files in parallel.
  • Cache expensive operations like date formatting.
  • Log renamed files to external files for rollback or audits.

Here’s an example using Java Streams:

import java.nio.file.*;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

public class ParallelRenamer {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("/path/to/your/images");
        AtomicInteger counter = new AtomicInteger(1);

        Files.list(dir)
            .filter(path -> path.toString().endsWith(".jpg"))
            .parallel()
            .forEach(path -> {
                String newName = String.format("img_%04d.jpg", counter.getAndIncrement());
                try {
                    Files.move(path, path.resolveSibling(newName));
                    System.out.println("Renamed to: " + newName);
                } catch (IOException e) {
                    System.err.println("Failed: " + path.getFileName());
                }
            });
    }
}

This approach improves throughput on multi-core systems and can be scaled for massive folders.

Conclusion

Automating file renaming with Java not only saves hours of manual labor but also provides a consistent, scriptable workflow—ideal for pre-processing images, preparing datasets, or organizing media libraries. From basic counter renaming to robust timestamping and pattern-based names, Java’s File and NIO APIs offer powerful tools to build fast and safe automation scripts.

 

Useful links: