利用文件目录遍历文件并将视频序号改为19开始(3.13回头看)

需求:

        将文件目录下的视频01、02...改为19、20...

代码:

简单实现代码:

import java.io.File;

public class Test {
    public static void main(String[] args) {
        File dir=new File("E:\\heimalearn\\aaa");

        //1.拿到下面的全部视频,一级文件对象
        File[] videos = dir.listFiles();

        //2.一个一个的找
        for (File video : videos) {
            //3.拿到它的名字,改成新名字
            String name=video.getName();
            String index=name.substring(0,name.indexOf("_"));
            String lastName=name.substring(name.indexOf("."));
            String newName=(Integer.valueOf(index)+18)+lastName;

            //4.正式改名
            video.renameTo(new File(dir,newName));
        }
    }
}

扩展的代码(回头看):

import java.io.File;

public class Test0306 {
    public static void main(String[] args) {
        // 指定文件夹路径
        String folderPath = "E:\\heimalearn\\aaa";
        File folder = new File(folderPath);

        // 获取文件夹中的所有文件
        File[] files = folder.listFiles();

        if (files != null) {
            int startNumber = 1; // 起始序号

            for (File file : files) {
                if (file.isFile() && isVideoFile(file)) {
                    // 获取文件扩展名
                    String extension = getFileExtension(file);

                    // 构建新的文件名
                    String newFileName = String.format("%03d.%s", startNumber, extension);//_改成了.应该是""里的原因,但是别乱改,_后面直接全没了
                    File newFile = new File(folderPath + File.separator + newFileName);

                    // 重命名文件
                    if (file.renameTo(newFile)) {
                        System.out.println("Renamed: " + file.getName() + " -> " + newFileName);
                        startNumber++;
                    } else {
                        System.out.println("Failed to rename: " + file.getName());
                    }
                }
            }
        } else {
            System.out.println("The folder is empty or does not exist.");
        }
    }

    // 判断文件是否为视频文件
    private static boolean isVideoFile(File file) {
        String[] videoExtensions = {".mp4", ".avi", ".mkv", ".mov", ".flv"};
        String fileName = file.getName().toLowerCase();
        for (String ext : videoExtensions) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    // 获取文件扩展名
    private static String getFileExtension(File file) {
        String fileName = file.getName();
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex != -1) {
            return fileName.substring(lastDotIndex + 1);
        }
        return "";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值