今天遇到这样一个情况,下载的视频中因为加入一串字符导致,md文件的图片找不到,改起来又特别麻烦,所以做这么一段代码去搞定它。
1 package program; 2 3 import java.io.File; 4 5 /** 6 * @author zsh 7 * @site https://qqzsh.top 8 * @create 2020-02-06 11:58 9 * @Description 批量修改文件名称 10 */ 11 public class Main9 { 12 13 //新字符串,如果是去掉前缀后缀就留空,否则写上需要替换的字符串 14 static String newString = ""; 15 //要被替换的字符串 16 static String oldString = "【瑞客论坛 www.ruike1.com】"; 17 //文件所在路径,所有文件的根目录 18 static String dir = "E:\\BaiduNetdiskDownload\\黑马头条项目 压缩打包版 - Java Springboot2.0(资料、代码。讲义)14天完整\\"; 19 20 public static void main(String[] args) { 21 //递归遍历此路径下所有文件夹 22 recursiveTraversalFolder(dir); 23 } 24 25 /** 26 * 递归遍历文件夹获取文件 27 */ 28 public static void recursiveTraversalFolder(String path) { 29 File folder = new File(path); 30 if (folder.exists()) { 31 File[] fileArr = folder.listFiles(); 32 if (null == fileArr || fileArr.length == 0) { 33 System.out.println("文件夹是空的!"); 34 return; 35 } else { 36 //文件所在文件夹路径+新文件名 37 File newDir = null; 38 //新文件名 39 String newName = ""; 40 //旧文件名 41 String fileName = null; 42 //文件所在父级路径 43 File parentPath = new File(""); 44 for (File file : fileArr) { 45 if (file.isDirectory()) { 46 //是文件夹,继续递归,如果需要重命名文件夹,这里可以做处理 47 System.out.println("文件夹:" + file.getAbsolutePath() + ",继续递归!"); 48 recursiveTraversalFolder(file.getAbsolutePath()); 49 } else { 50 //是文件,判断是否需要重命名 51 fileName = file.getName(); 52 parentPath = file.getParentFile(); 53 //文件名包含需要被替换的字符串 54 if (fileName.contains(oldString)) { 55 //新名字 56 newName = fileName.replaceAll(oldString, newString); 57 //文件所在文件夹路径+新文件名 58 newDir = new File(parentPath + "/" + newName); 59 //重命名 60 file.renameTo(newDir); 61 System.out.println("修改后:" + newDir); 62 } 63 } 64 } 65 } 66 } else { 67 System.out.println("文件不存在!"); 68 } 69 } 70 }
原文:https://www.cnblogs.com/zsh-blogs/p/12268251.html