代码实现
主方法体: (具体的步骤可看代码注释)
public static void test() {
// 创建Scanner对象并传入标准输入流(键盘)作为参数
Scanner scanner = new Scanner(System.in);
System.out.print("请输入需要处理的md文件目录路径:");
// 读取用户输入的字符串
String input = scanner.nextLine();
System.out.println("将在该目录下新建一个images目录");
scanner.close();
String directPath = input;
String imagesPath = directPath + "\\images";
File imagesDirect = new File(imagesPath);
if (!imagesDirect.exists()){
imagesDirect.mkdirs();
}else if (!imagesDirect.isDirectory()){
imagesDirect.mkdirs();
}
File file = new File(directPath);
String[] list = file.list();
if (Objects.isNull(list)){
throw new RuntimeException("空目录");
}
for(String fileName : list){
// 只处理md文件
if (!fileName.contains(".md")){
continue;
}
// try catch一下保证程序运行不报错,即使有某个文件处理过程中出问题不影响其他文件处理
try{
String filePath = directPath + "\\" + fileName;
// 将该md文件内容读取出来存进List<String>中方便后续处理
List<String> lines = readFile(filePath);
// 建一个新的List<String>用于接受处理好的内容
List<String> newLines = new LinkedList<>();
// 开始对每一行内容进行处理
for (String line : lines) {
// 图片md的格式是这样的:
if (StrKit.isNotBlank(line) && line.startsWith("![image")) {
int start = line.indexOf("(") + 1;
int end = line.indexOf(")");
// 取出图片路径
String imagePath = line.substring(start, end);
// 已经在images目录下的照片跳过,不进行处理
if (!imagePath.startsWith("images") ) {
File image = new File(imagePath);
String copyImagePath = imagesPath + "\\" + image.getName();
File copyImage = new File(copyImagePath);
// 将存在c盘中的图片复制出来到images目录下
FileKit.copy(image, copyImage, true);
// 这是新相对路径取代原有c盘绝对的路径
String positiveImagePath = "images\\" + image.getName();
line = line.replace(imagePath, positiveImagePath);
}
}
// 将内容存进新list
newLines.add(line);
}
// 将处理好的md内容重新写进md文件中
writeFile(newLines,filePath);
System.out.println(StrKit.format("文件:{}已处理成功",fileName));
}catch (Exception e){
System.out.println(StrKit.format("文件:{}处理异常,异常信息:{}",fileName,e.getMessage()));
}
}
}
/**
* 读取文件
* @param filePath
* @return
*/
public static List<String> readFile(String filePath){
List<String> lines = new LinkedList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath)))
{
String lineStr;
while ((lineStr = reader.readLine())!=null) {
lines.add(lineStr);
}
}catch (Exception e){
e.printStackTrace();
}
return lines;
}
/**
* 将修改的内容写回文件
* @param lines
* @param filePath
*/
public static void writeFile(List<String> lines, String filePath){
try(BufferedWriter reader = new BufferedWriter(new FileWriter(filePath))){
for (String line : lines){
reader.write(line);
reader.newLine();
}
}catch (Exception e){
e.printStackTrace();
}
}
使用方法
idea运行启动、java -jar xxx.jar 启动
md文件内容中关于图片的路径也将会自动修改成相对路径(images/xxxx.jpg)
操作完成!