JAVA实现文件批量重命名

package fileRename;

import java.io.File;

/**
 * 文件批量重命名类
 * 
 * @author Administrator
 * 
 */
public class CHBRenamer {
    public static void main(String[] args) {

        // 获取要批量修改的文件父目录
        String path = "";

        // 获得文件列表
        File file = new File(path);
        String[] files = file.list();

        // 外部初始化新文件名和旧文件名 及 新的文件载体 供循环中使用
        String newName = "";
        String oldName = "";
        File f = null;

        // 循环可以得到每个文件名称,并进行一系列的操作
        for (int i = 0; i < files.length; i++) {

            // 获得文件旧名称
            oldName = files[i];
            // 判断是否符合自己要修改名称的标准(原文件名是否包含自己不想要的字段),如果不符合,继续进行下一次循环
            if (!oldName.contains("动力节点")) {
                continue;
            }

            // 初始化新文件名(即以什么为前缀)
            newName = "";

            // 得到旧文件名称第一次出现某字符的下标(注:String下标从0开始)
            int index = oldName.indexOf(".");
            // 取0到此字符之间的字符串
            String s1 = oldName.substring(0, index + 1);
            // 取旧文件中 某个字符的后面+n位开始 到 最后一个字符之间 的字符串(包含那个(字符+n)位的字符)
            String s2 = oldName.substring(oldName.indexOf("节") + 2,
                    oldName.length());
            // "."第一次出现的下标

            // 与初始化的新文件名拼起来
            newName += s1;
            newName += s2;
            System.out.println(newName);

            // 先通过名字拿到旧文件
            f = new File(path + "/" + oldName);
            // 将旧文件改名
            f.renameTo(new File(path + "/" + newName));
        }
    }
}

 

猜你喜欢

转载自blog.csdn.net/wt122694/article/details/81173195