java 批量重命名文件

package pers.lsy.util.io;


import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RenameFile {

    public static void main(String[] args) {
        RenameFile folder = new RenameFile();
        String filePath = "";
        //替换空格
		folder.replaceFileName(new File(filePath),"[/|*|\\\\|?|:|<|>|\\s+]","");
        //数字后添加空格
		folder.renameFiles(new File(filePath), "\\d*", "");
    }

    /**
     * 重命名文件去除多余文件名字内的文字
     *
     * @param file    文件
     * @param oldName 文件名中需要修改的内容
     * @param newName 将需要修改的内容替换为指定内容
     */
    public void replaceFileName(File file, String oldName, String newName) {
        File[] files = null;
        File newfile = null;
        if (file.isDirectory()) {
            files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                renameFiles(files[i], oldName, newName);
            }
        } else {
            // 获取新生成的文件名
//			String newstr = file.getAbsolutePath().replaceAll(oldName, newName);
            String newstr = file.getName().replaceAll(oldName, newName);
            newfile = new File(file.getParent(), newstr);
            System.out.println(newfile.getAbsolutePath());
            // 重命名文件
			file.renameTo(newfile);

        }
    }

    public void renameFiles(File file, String regex, String newName) {
        File[] files = null;
        File newfile = null;
        if (file.isDirectory()) {
            files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                renameFiles(files[i], regex, newName);
            }
        } else {
            // 获取新生成的文件名
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(file.getName());
            if (matcher.find()) {
                String newstr = file.getName().replaceAll(regex, newName);
                newfile = new File(file.getParent(), matcher.group()+" "+newstr);
                System.out.println(newfile.getAbsolutePath());
                // 重命名文件
                file.renameTo(newfile);
            }

        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

li.siyuan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值