批量文件重命名

上代码

package test;

import java.io.File;
import java.io.IOException;

public class NewFilenName {

    public static void main(String[] args) throws IOException {
        String root ="D:\\svg";
        File oldName = new File(root);
        File[] arrFiles = oldName.listFiles();
        for(int i=0;i<arrFiles.length;i++) {
            
            File file = arrFiles[i];
            String fName = file.getAbsolutePath();
            System.out.println("原文件名:"+fName +i);
            if(fName.endsWith(".svg")) {
                if(file.isFile()) {
                    rName(root, file ,i);
                }
            }
        }

    }
    
    /**
     * 重命名
     * @param root 暂时未使用
     * @param file 旧的文件或目录
     * @param i 当前文件下标
     * @throws IOException
     */
    public static void rName(String root,File file,int i) throws IOException {
        // 新的文件或目录
        File newName = new File("D:\\svg\\new\\gjj_"+i+".svg");
        if (newName.exists()) {  //  确保新的文件名不存在
            throw new java.io.IOException("file exists");
        }
        if(file.renameTo(newName)) {
            System.out.println("已重命名"+newName);
        } else {
            System.out.println("Error");
        }
    }

}

 

posted @ 2022-05-17 15:47  天意天雨  阅读(163)  评论(0编辑  收藏  举报