-->
侧边栏壁纸
博主头像
断钩鱼 博主等级

行动起来,活在当下

  • 累计撰写 28 篇文章
  • 累计创建 34 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

批量修改文件名

halt
2020-03-13 / 0 评论 / 0 点赞 / 1892 阅读 / 0 字

最近找到的资源老是带有一些网站的签名

package top.mengshuo;

import java.io.File;
import java.util.Scanner;

/**
 * 文件名替换
 *
 * @author mengshuo
 * @since 1.0
 */
public class FilesRenameUtil {
    public static void main(String[] args) {
        String path;
        String oldContent;
        String newContent;
        boolean flag;
        Scanner scanner = new Scanner(System.in);
        System.out.println("==== 请输入扫描路径 ====");
        path = scanner.nextLine();
        System.out.println("==== 请输入需要替换的文件名字段(sources) ====");
        oldContent = scanner.nextLine();
        System.out.println("==== 请输入替换为什么字段(target) ====");
        newContent = scanner.nextLine();
        System.out.println("==== 是否对子孙目录更改 Y 更改 其他不更改 ====");
        flag = scanner.nextLine().toUpperCase().equals("Y");

        System.out.printf(
                "请确认:\n 扫描路径: %s ,源文件文件名字段(支持正则): %s ,目标文件字段: %s ,否对子孙目录更改: %s \n 输入 Y 执行文件名批量替换 其他取消执行 \n",
                path, oldContent, newContent, (flag ? "更改" : "不更改")
        );
        if (scanner.nextLine().toUpperCase().equals("Y")) {
            fileReName(path, oldContent, newContent, flag);
        } else {
            System.out.println("取消执行");
        }


    }

    /**
     * 将文件夹内所有文件名称删除或者修改为指定内容 包括文件夹
     *
     * @param path       扫描路径
     * @param oldContent 旧的的文件名字段
     * @param newContent 新的文件名字段
     * @param flag       是否对子孙目录更改
     */
    public static void fileReName(String path, String oldContent, String newContent, Boolean flag) {
        File file = new File(path);
        //当文件目录存在时
        if (file.exists()) {
            //获取文件列表
            File[] files = file.listFiles();
            //当文件列表不为空时
            if (files != null && files.length > 0) {
                //遍历文件内容
                for (File f : files) {
                    //获取文件名
                    String fileName = f.getName();

                    //将文件名重命名
                    String newFileName = fileName.replaceAll(oldContent, newContent);
                    System.out.println("当前文件名称:" + fileName);
                    if (!fileName.equals(newFileName)) {
                        //对文件进行重命名操作
                        File olderFile = new File(path + "\\" + fileName);
                        File newFile = new File(path + "\\" + newFileName);
                        olderFile.renameTo(newFile);
                        System.out.println("新的名称:" + newFileName + "\n");
                    } else {
                        System.out.println("文件名称不符合更改条件!\n");
                    }
                    if (f.isDirectory() && flag) {
                        fileReName(path + "\\" + newFileName, oldContent, newContent, true);
                    }
                }
            }
        } else {
            System.err.println("目录不存在");
        }
    }

}

0
博主关闭了所有页面的评论