JAVA批量修改文件名称

JAVA批量修改文件名称

package com.base.task;

import com.base.common.utils.UUIDUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author zhangwei
 * @date 2020/9/25 15:04
 */
public class FileOperate {

    // 文件路径
    final static String FILE_PATH = "C:\\Users\\zhangwei\\Desktop\\xmyeditor\\";

    // 前缀
    final static String FILE_NAME = "collect_";

    public static void main(String[] args) {
        try {
            readfile(FILE_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readfile(String filepath) throws FileNotFoundException, IOException {
        try {
            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        //修改文件名称
                        fileNenameTo(FILE_NAME+UUIDUtils.UUIDReplace(), readfile);
                    } else if (readfile.isDirectory()) {
                        readfile(filepath + "\\" + filelist[i]);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        }
    }

    private static void fileNenameTo(String fileName, File readfile) {
        String name = readfile.getName();
        //获取文件名称或者自定义
        //获取文件后缀,保留原有文件格式
        String suffix = name.substring(name.lastIndexOf("."), name.length());
        File saveFile = new File(FILE_PATH + fileName + ".jpg");
        readfile.renameTo(saveFile);
    }

}

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://xianyum.cn/archives/work-1

Buy me a cup of coffee ☕.