使用Java11批量给文件夹下的视频添加数字编号

java 复制代码
package com.alvin.test;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

public class Test {

    // 常见的视频文件扩展名
    private static final Set<String> VIDEO_EXTENSIONS = Set.of(
            "mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v",
            "mpg", "mpeg", "3gp", "mts", "m2ts", "ts", "vob", "ogv", "rm","rmvb","divx"
    );

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            // 获取用户输入
            System.out.print("请输入文件夹路径: ");
            String folderPath = scanner.nextLine().trim();

            System.out.print("请输入起始数字: ");
            int startNumber = Integer.parseInt(scanner.nextLine().trim());

            System.out.print("请输入结束数字: ");
            int endNumber = Integer.parseInt(scanner.nextLine().trim());

            // 验证输入
            if (startNumber > endNumber) {
                System.out.println("错误:起始数字不能大于结束数字");
                return;
            }

            Path directory = Paths.get(folderPath);
            if (!Files.exists(directory) || !Files.isDirectory(directory)) {
                System.out.println("错误:指定的路径不存在或不是目录");
                return;
            }

            // 收集视频文件
            List<Path> videoFiles = new ArrayList<>();
            Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    if (isVideoFile(file)) {
                        videoFiles.add(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });

            // 验证数字范围
            int fileCount = videoFiles.size();
            int numberRange = endNumber - startNumber + 1;

            if (fileCount > numberRange) {
                System.out.printf("警告:文件数量(%d)大于数字范围(%d),部分文件将不会被重命名%n",
                        fileCount, numberRange);
            } else if (fileCount < numberRange) {
                System.out.printf("警告:文件数量(%d)小于数字范围(%d),数字将不会用完%n",
                        fileCount, numberRange);
            }

            // 排序文件(按文件名)
            videoFiles.sort(Comparator.comparing(path -> path.getFileName().toString()));

            // 确认操作
            System.out.printf("找到 %d 个视频文件,将从 %d 到 %d 进行重命名%n",
                    fileCount, startNumber, Math.min(endNumber, startNumber + fileCount - 1));
            System.out.print("是否继续?(y/n): ");
            String confirmation = scanner.nextLine().trim().toLowerCase();

            if (!confirmation.equals("y") && !confirmation.equals("yes")) {
                System.out.println("操作已取消");
                return;
            }

            // 执行重命名
            renameFiles(videoFiles, startNumber, Math.min(endNumber, startNumber + fileCount - 1));

            System.out.println("重命名完成!");

        } catch (NumberFormatException e) {
            System.out.println("错误:请输入有效的数字");
        } catch (InvalidPathException e) {
            System.out.println("错误:无效的路径格式");
        } catch (IOException e) {
            System.out.println("IO错误: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("发生错误: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    private static boolean isVideoFile(Path file) {
        String fileName = file.getFileName().toString();
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            String extension = fileName.substring(dotIndex + 1).toLowerCase();
            return VIDEO_EXTENSIONS.contains(extension);
        }
        return false;
    }

    private static void renameFiles(List<Path> files, int start, int end) throws IOException {
        int currentNumber = start;

        for (Path file : files) {
            if (currentNumber > end) {
                break;
            }

            String fileName = file.getFileName().toString();
            Path parentDir = file.getParent();

            // 构建新文件名
            String newFileName = currentNumber + "." + fileName;
            Path newPath = parentDir.resolve(newFileName);

            // 检查目标文件是否已存在
            if (Files.exists(newPath)) {
                System.out.printf("警告:文件 %s 已存在,跳过重命名 %s%n",
                        newFileName, fileName);
                continue;
            }

            try {
                // 执行重命名
                Files.move(file, newPath, StandardCopyOption.REPLACE_EXISTING);
                System.out.printf("重命名: %s -> %s%n", fileName, newFileName);
                currentNumber++;
            } catch (IOException e) {
                System.out.printf("重命名失败 %s: %s%n", fileName, e.getMessage());
            }
        }
    }
}