Java实现递归修改文件名字/复制文件

渡星河
2024-01-30 / 0 评论 / 11 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年01月30日,已超过232天没有更新,若内容或图片失效,请留言反馈。

代码示例

package com.zhkt.ostrich;

/**
 * Author: duGalaxy
 * Date: 2023/09/11/11:03
 * Description:
 */
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class test {
    public static void main(String[] args) throws IOException {
        String directoryPath = "F:\\A公司项目\\汐游游戏\\xy-epg\\game"; // 替换为你的目录路径
        renameFiles(directoryPath);
    }

    public static void renameFiles(String directoryPath) throws IOException {
        File directory = new File(directoryPath);
        File[] files = directory.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    renameFile(file);
                } else if (file.isDirectory()) {
                    // 递归调用自身处理子文件夹
                    renameFiles(file.getAbsolutePath());
                }
            }
            System.out.println(count);
        }
    }

    static int count = 0;
    public static void renameFile(File file)  {
        String originalName = file.getName();
        String path = file.getPath();
        if (path.contains(".mp3")){
            // 包含mp3直接复制粘贴换个后缀
            try {
                Files.copy(Paths.get(path),Paths.get(path.replaceAll(".mp3",".mp4")));
            } catch (IOException e) {
                return;
            }
        }
//        System.out.println();
//        System.out.println(originalName);
//        String newName = originalName.replaceAll("探险岛", "txd");
//        count++;

//        if (!originalName.equals(newName)) {
//            String newPath = file.getParent() + File.separator + newName;
//            File newFile = new File(newPath);
//
//            if (file.renameTo(newFile)) {
//                System.out.println("文件重命名成功:" + originalName + " --> " + newName);
//            } else {
//                System.out.println("文件重命名失败:" + originalName);
//            }
//        }
    }
}

1

评论 (0)

取消