Java 8 rename multiple files recursively

Problem

If you need to do simple file name transformation for multiple files like:

song1.txt -> music1.txt
song2.txt -> music2.txt
song3.txt -> music3.txt

Then you can use the new Java File I/O (NIO.2).

Solution

Below you can find a sample code that find all files (recursively) in folder:

"C:\Users\user\Desktop\folder"

Then print all names. After that it check each file name (going in sub folders recursively) and search for
song. And replace it if it has otherwise do nothing. The depth of renaming is 3 levels.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Convert {
    public static void main(java.lang.String[] args) {
        
        //working folder
        String dir = "C:\\Users\\user\\Desktop\\folder";
        //recursively list files before renaming
        listFiles(dir);
        //rename files - replace text in the name with song.text
        renameFiles(dir, "song", "music");
        //recursively list files after renaming
        listFiles(dir);
    }


    public static void listFiles(String dir) {
        try {
            Files.find(Paths.get(dir),
                    Integer.MAX_VALUE,
                    (filePath, fileAttr) -> fileAttr.isRegularFile())
                    .forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void renameFiles(String dir, String replace, String replaceBy) {
        try {
            try (Stream<Path> stream = Files.find(Paths.get(dir), 3,
                    (path, attr) -> String.valueOf(path).endsWith(".txt"))) {
                stream.map(String::valueOf).forEach(item -> {
                            try {
                                Files.move(new File(item).toPath(), new File(item.replace(replace, replaceBy)).toPath());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                );
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Note : You may fave error like:

use of api documentation since 1.7+
use of api documentation since 1.8+

Which means that you need to change your java compiler version to use newer one. You can find more here:

Java 8 Warning:java: target source value 1.5 is obsolete

Related Article