文件批量重命名
背景: 下载别人的markdown 文件,里面的图片是绝对地址,导致不显示。
修改成相对地址即可成功显示。
利用正则表达式选取需要替换的部分,替换成你需要更改的新文件名字
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String[] args) {
// 需要修改的文件所在的文件夹,按需更改
String filePath = "D:\\image\\";
File file = new File(filePath);
// 正则表达式,这里只是提供参考。每个人的需求不一定相同。
// 我这里是将 %asdfasasdfasdfasdfadfasf%123.png
// 修改成 imgae-123.png
String p = "(%.*%)";
Pattern r = Pattern.compile(p);
// 列出该文件夹下所有文件
File[] list = file.listFiles();
if (file.exists() && file.isDirectory()) {
if (list != null) {
for (File value : list) {
// 文件名
String line = value.getName();
// 现在创建 matcher 对象
Matcher m = r.matcher(line);
// 匹配到了则修改
if (m.find()) {
// 文件的新名字
String newLine = line.replaceAll(m.group(1), "image-");
// 对比修改前后文件名称
System.out.println("Found value: " + m.group(0));
System.out.println(newLine + "\n");
// 将文件重命名
File dest = new File(filePath + newLine);
if( value.renameTo(dest)){
System.out.println("修改成功");
}else{
System.out.println("文件修改失败");
}
} else {
System.out.println("NO MATCH");
}
}
}
}
}
}