You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java批量替换文件名中的指定字符(!替换为_)

批量替换文件名中的指定字符(Java实现)

我来帮你改造现有代码,实现批量替换文件名里!为_的功能,保证只修改目标字符、完全保留文件名其他部分:

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class BatchRenameFiles {
    public static void main(String[] args) {
        // 替换的目标目录,改成你实际的文件夹路径
        String targetDir = "./your-target-folder";
        // 需要替换的旧字符和新字符
        char oldChar = '!';
        char newChar = '_';

        File dir = new File(targetDir);
        if (!dir.isDirectory()) {
            System.err.println("指定路径不是有效目录!");
            return;
        }

        // 获取目录下所有文件(不含子目录,如需递归可扩展)
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            System.out.println("目录下没有文件!");
            return;
        }

        for (File file : files) {
            if (file.isFile()) { // 只处理文件,跳过目录
                String oldName = file.getName();
                // 先检查是否有需要替换的字符,避免无意义操作
                if (oldName.contains(String.valueOf(oldChar))) {
                    String newName = oldName.replace(oldChar, newChar);
                    Path oldPath = file.toPath();
                    Path newPath = Paths.get(dir.getAbsolutePath(), newName);

                    try {
                        // 使用NIO的Files.move更可靠,支持覆盖同名文件(可按需调整参数)
                        Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
                        System.out.println("已完成重命名:" + oldName + " -> " + newName);
                    } catch (Exception e) {
                        System.err.println("重命名失败:" + oldName);
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("无需处理:" + oldName);
                }
            }
        }
    }
}

关键细节说明:

  • 路径配置:把targetDir改成你实际要处理的文件夹路径,比如"C:/Users/xxx/Documents/test-files"
  • 精准替换:oldName.replace(oldChar, newChar)只会替换文件名中所有的!为_,其他字符完全保留,完全符合你的需求
  • 安全校验:先判断路径有效性、文件是否存在,避免运行时出错
  • 稳定重命名:用Files.move替代老旧的File.renameTo,后者在跨文件系统时容易失败,NIO API更可靠,还支持处理同名文件的场景
  • 效率优化:先检查文件名是否包含目标字符,跳过不需要修改的文件

可选扩展:递归处理子目录

如果需要处理文件夹下的所有子目录文件,可以添加一个递归方法:

private static void processFiles(File dir, char oldChar, char newChar) {
    File[] files = dir.listFiles();
    if (files == null) return;
    for (File file : files) {
        if (file.isDirectory()) {
            processFiles(file, oldChar, newChar); // 递归处理子目录
        } else if (file.isFile()) {
            // 这里放入之前的重命名逻辑
        }
    }
}

然后在main方法里调用processFiles(dir, oldChar, newChar)即可。

内容的提问来源于stack exchange,提问作者Kayaan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:09:10