昨天做实验,采了很多图,由于使用了之前版本的采图程序,导致图片的命名全部错了,就是在小于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"复制代码