java小功能:批量修改文件名

先上代码

 public static int changeFileName(File file, String str) {
  /*            是否存在
                是否为目录
                目录是否为空
                不为空进入循环
                是文件,修改名字*/
        int i = 1;
        if (!file.exists()) return 0;
        /*if (file == null) return 0;*/
        if (file.isFile()) {
            //为文件
            String[] suf = null;
            suf = file.getName().split("\\.");
            File newf = new File(file.getParentFile(), str +  "." + suf[suf.length - 1]);
            file.renameTo(newf);
            return 0;

        }
        int count = file.list().length;

        for (String f1 : file.list()) {
            File oldFile = new File(file, f1);
            System.out.println("old File(" + count + "):" + oldFile.getName());
            if(oldFile.isDirectory()) changeFileName(oldFile,str);
            if (oldFile.isFile()) {
                String[] suffix = null;
                suffix = f1.split("\\.");
                File newFile = null;
                if (suffix.length > 1) {
                    newFile = new File(oldFile.getParentFile(), str + i + "." + suffix[suffix.length - 1]);
                } else {
                    newFile = new File(oldFile.getParentFile(), str + i);
                }
                System.out.println("new File(" + count + "):" + newFile.getName());
                i++;
                oldFile.renameTo(newFile);
            }

        }


        return i;
    }

思路:
1.传入需要修改名字的文件夹路径或者文件名,新的文件名。
2.首先判断FIle是否为真实的路径,也就是是否存在。
如果不存在,直接return。如果存在就继续
3.然后判断File是否为目录,如果为目录就获取文件的长度并且进行for循环。
3.1在for循环中判断File为目录还是文件,如果为目录,直接调用本方法
3.2如果为文件,就获取文件的后缀名,创建新File,并且以文件名+序号+.+后缀名进行命名

写完了发现有个bug,如果目录有子文件,在子文件中添加两次文件,那么第二次添加的文件有部分不会被改名.再运行一次代码又可以了。没找到错误原因,希望大神指点!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值