栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java】批量修改文件名(支持多目录,递归目录)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java】批量修改文件名(支持多目录,递归目录)

import java.io.File;

public class ChangeFileName {
    public static void main(String[] args) {
        // 要修改的文件所在目录
        String path = "C:\Users\Pangpd\Desktop\检测单";
        changeFileName(path);
    }

    public static void changeFileName(String path) {
        File folder = new File(path);
        if (folder.exists()) {
            File[] fileArr = folder.listFiles();
            if (null == fileArr || fileArr.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file : fileArr) {
                    if (file.isDirectory()) {//是文件夹,继续递归,如果需要重命名文件夹,这里可以做处理
                        System.out.println("文件夹:" + file.getAbsolutePath() + ",继续递归!");
                        changeFileName(file.getAbsolutePath());
                    } else {
                        //是文件,判断是否需要重命名
                        File parentPath = new File("");//文件所在父级路径
                        parentPath = file.getParentFile();
                        String fileName = file.getName(); //旧名
                        // 获取文件名前半部分(车牌号)
                        String firstName = fileName.substring(0, fileName.indexOf("("));
                        // 获取文件名前后部分(检测时间)
                        String sedName = fileName.substring(fileName.indexOf("(") + 1, fileName.indexOf(")"));
                        //重新定义名字
                        String newName = sedName + "(" + firstName + ")" + ".docx";
                        File newFile = new File(parentPath + "/", newName);
                        System.out.println(fileName + "-->" + newName);
                        //进行重命名操作
                        if (file.renameTo(newFile)) {
                            System.out.println(file.getName() + "重命名成功---");
                        } else {
                            System.out.println(file.getName() + "重命名失败+++");
                        }
                    }
                }
            }
        }
    }
}

参考链接:
https://www.cnblogs.com/codekjm/p/9615815.html
https://blog.csdn.net/gjs935219/article/details/104264925

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/776436.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号