JAVA批量修改文件夹中的文件名

3 篇文章 0 订阅
2 篇文章 0 订阅
import java.io.File;
/**
 * 批量重命名文件
 *
 * @author YueYaobin
 * @create 2021/4/20
 */
public class updateFileName {


    public static void main(String[] args) {

        //文件所在路径,所有文件的根目录,记得修改为你电脑上的文件所在路径
        String dir = "F:\\学习";
        //新字符串,如果是去掉前缀后缀就留空,否则写上需要替换的字符串
        String newString = "";
        //要被替换的字符串
        String oldString = "test";
        //递归遍历此路径下所有文件夹
        recursiveTraversalFolder(dir,newString,oldString);
    }

    /**
     * 递归遍历文件夹获取文件
     * @param path
     * @param newString
     * @param oldString
     */
    public static void recursiveTraversalFolder(String path,String newString,String oldString) {
        File folder = new File(path);
        if (folder.exists()) {
            File[] fileArr = folder.listFiles();
            if (null == fileArr || fileArr.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                //文件所在文件夹路径+新文件名
                File newDir = null;
                //新文件名
                String newName = "";
                //旧文件名
                String fileName = null;
                //文件所在父级路径
                File parentPath = new File("");
                for (File file : fileArr) {
                    //是文件夹,继续递归,如果需要重命名文件夹,这里可以做处理
                    if (file.isDirectory()) {
                        System.out.println("文件夹:" + file.getAbsolutePath() + ",继续递归!");
                        recursiveTraversalFolder(file.getAbsolutePath(),newString,oldString);
                    } else {//是文件,判断是否需要重命名
                        fileName = file.getName();
                        parentPath = file.getParentFile();
                        //文件名包含需要被替换的字符串
                        if (fileName.contains(oldString)) {
                            //新名字
                            newName = fileName.replace(oldString, newString);
                            //文件所在文件夹路径+新文件名
                            newDir = new File(parentPath + "/" + newName);
                            //重命名
                            file.renameTo(newDir);
                            System.out.println("修改后:" + newDir);
                        }
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值