java重命名代码大全,用Java代码批量重命名文件

昨天做实验,采了很多图,由于使用了之前版本的采图程序,导致图片的命名全部错了,就是在小于10的数字前面没有加0,如02。导致接下来跑另一个程序的时候读图顺序总是出错,故写了一个代码批量重命名了这些文件。由于正则表达式不会写,只能用了最笨的方法来做。

import java.io.File;

import java.util.ArrayList;

import java.util.List;

public class Test {

public static void main(String[] args) {

String path = "F:/20180924L1/1000hz_2"; // 要批量修改的文件所在的目录

File file = new File(path);

boolean isDirectory = file.isDirectory();

if (!isDirectory) { // 如果不是文件夹,就返回

System.out.println(path + "不是文件夹!");

return;

}

String[] files = file.list();

File f = null;

String newFileName = ""; // 新的文件名字

String oldFileName = ""; // 旧的文件名字

for (int i = 0; i < files.length; i++) { // 遍历该文件夹下的所有文件

oldFileName = files[i];

newFileName = oldFileName;

boolean x1 = false;

boolean x2 = false;

int a, b, c, d;

a = oldFileName.indexOf("_");

b = oldFileName.indexOf(".");

c = oldFileName.lastIndexOf("_");

d = oldFileName.indexOf(".", c);

String snum1 = oldFileName.substring(a + 1, b);

String snum2 = oldFileName.substring(c + 1, d);

if (Integer.parseInt(snum2) < 10) {

newFileName = newFileName.substring(0, c + 1) + "0" + newFileName.substring(c + 1);

x1 = true;

}

if (Integer.parseInt(snum1) < 10) {

newFileName = newFileName.substring(0, a + 1) + "0" + newFileName.substring(a + 1);

x2 = true;

}

// 如果文件名没变,跳过它

if (!(x1 || x2)) {

continue;

}

// 将修改后的文件保存在原目录下

f = new File(path + "/" + oldFileName);

f.renameTo(new File(path + "/" + newFileName));

}

}

}

复制代码

把一大批类似于

String s = "1000hz_12.0v1_6.0v2.jpg";

复制代码

这样的文件名重命名为

"1000hz_12.0v1_06.0v2.jpg"复制代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值