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

如何用Groovy/Java脚本将文件名中的日期替换为当前日期

Groovy 实现

Groovy 对文件和字符串处理做了大量语法简化,代码更简洁:

import java.io.File

def processFiles(String dirPath) {
    def dir = new File(dirPath)
    if (!dir.exists() || !dir.isDirectory()) {
        println "目录不存在或非法"
        return
    }
    // 遍历目录下所有文件
    dir.eachFile { file ->
        if (!file.isFile()) return
        // 拆分文件名和后缀
        def extSplitIndex = file.name.lastIndexOf('.')
        def nameNoExt = extSplitIndex > 0 ? file.name.take(extSplitIndex) : file.name
        def ext = extSplitIndex > 0 ? file.name.drop(extSplitIndex) : ""

        // 自定义处理规则:示例为按下划线拆分任意长度的文件名,取倒数第二段作为业务标识
        // 可替换为正则匹配、固定位置截取等任意规则
        def segments = nameNoExt.split('_')
        if (segments.size() < 2) {
            println "跳过不符合规则文件:${file.name}"
            return
        }
        def bizId = segments[-2]
        // 生成输出文件名,可按需调整规则
        def outputName = "${bizId}_${System.currentTimeMillis()}${ext}"
        def outputFile = new File(file.parent, outputName)

        // 替换为实际业务逻辑:比如内容转换、重命名等
        file.copyTo(outputFile, true)
        println "处理完成:${file.name} -> ${outputName}"
    }
}

// 调用示例,传入目标文件目录
processFiles("/your/target/directory")

Java 实现

纯Java原生实现,无需额外依赖:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class FileNameProcessor {
    public static void processFiles(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("目录不存在或非法");
            return;
        }
        File[] files = dir.listFiles(File::isFile);
        if (files == null) return;

        for (File file : files) {
            String fileName = file.getName();
            int extSplitIndex = fileName.lastIndexOf('.');
            String nameNoExt = extSplitIndex > 0 ? fileName.substring(0, extSplitIndex) : fileName;
            String ext = extSplitIndex > 0 ? fileName.substring(extSplitIndex) : "";

            // 自定义处理规则,和上面Groovy版本逻辑一致
            String[] segments = nameNoExt.split("_");
            if (segments.length < 2) {
                System.out.println("跳过不符合规则文件:" + fileName);
                continue;
            }
            String bizId = segments[segments.length - 2];
            String outputName = bizId + "_" + System.currentTimeMillis() + ext;
            File outputFile = new File(file.getParent(), outputName);

            try {
                // 替换为实际业务逻辑
                Files.copy(file.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                System.out.println("处理完成:" + fileName + " -> " + outputName);
            } catch (IOException e) {
                System.out.println("处理失败:" + fileName + ",错误:" + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        processFiles("/your/target/directory");
    }
}

规则调整说明

如果需要适配你的具体文件名规则,可以灵活修改处理逻辑:

  • 按固定字符拆分:修改split的分隔符即可
  • 正则匹配任意长度文件名:比如要提取任意前缀后跟着的8位日期,可使用正则^.*_(\\d{8})\\..*$,直接提取分组内容即可
  • 固定位置截取:不需要管总长度,直接从文件名前后指定位置截取对应字符即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:12:01