Java 批量重命名文件

  以下实例演示了使用java I/O流读取文件夹中所有的文件名,并基于for循环使用 File 类的 oldFile.renameTo(newFile) 方法批量重命名文件。

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.HashSet;
import java.util.Set;
import java.util.stream.Stream;

public class RenameFiles {
    private static Set<String> specifiedKeywords = new HashSet<>();

    public static void main(String[] args) {
        // 需要被替换的关键词,为空时不替换
        specifiedKeywords.add("Wiener");
        specifiedKeywords.add("汉声中国传统童话");
        // 获取要批量重命名的文件目录
        String path = "/Users/Music/你的文件目录";
        walkRename(path);
    }

    public static void walkRename(String targetPath) {
        Path dir = Paths.get(targetPath);
        try (Stream<Path> paths = Files.walk(dir)) {
            paths.forEach(path -> {
                if (Files.isRegularFile(path)) {
                    // 初始化新文件名,命名规则请根据需求自定义,以剔除指定字符串为例进行演示
                    ifRename(new File(path.toString()));
                } else if (Files.isDirectory(path)) {
                    // 是目录,不重命名
                    System.out.println("Directory: " + path);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件名包含关键词时替换
     * @param oneFile 待重命名的文件
     * @return true 替换成功
     */
    private static boolean ifRename(File oneFile) {
        String fileName = oneFile.getName();
        String parentPath = oneFile.getParent();
        for (String match : specifiedKeywords) {
            // 包含指定关键词时才重命名
            if (fileName.indexOf(match) >= 0) {
                // 通过路径+名字拿到旧文件
                String newFileName = fileName.replaceAll(match, "");
                String newFileObjName = parentPath + "/" + newFileName;
                boolean ret = oneFile.renameTo(new File(newFileObjName));
                System.out.println("旧File: " + fileName);
                System.out.println("新File名: " + newFileObjName + ",替换结果 = " + ret);
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }
}
posted @ 2022-09-17 09:59  楼兰胡杨  阅读(463)  评论(0)    收藏  举报