0%

java批处理之微博图床链接加标签

前因后果

微博图床加了防盗链,有一个缓兵之计是给所有<img>标签加上一个属性:referrerpolicy="no-referrer"

博客里插入了非常多图片,手动添加是不可能的,我们来用java批处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package sample;

import java.io.*;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MarkDownModify {
private final static Pattern PATTERN = Pattern.compile("(.*?)(<img.+>)(.*?)");

public static void addReferrerPolicy(File directory) throws IOException {
for (File file : Objects.requireNonNull(directory.listFiles())) {
modify(file);
}
}

private static void modify(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
line = regex(line);
content.append(line).append("\n");
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content.toString());
writer.flush();
}

private static String regex(String line) {
Matcher matcher = PATTERN.matcher(line);
if (matcher.matches()) {
String s1 = matcher.group(1);
String s2 = matcher.group(2);
String s3 = matcher.group(3);
s2 = "<img " + "referrerpolicy=\"no-referrer\" " + s2.substring(5);
return s1 + s2 + s3;
} else {
return line;
}
}
}

图形界面

我用javaFX给这段批处理程序写了一个图形界面:

先选择md文件所在的目录,之后点击Execute按钮执行批处理,点击help查看帮助。

源码已经上传到了github:

https://github.com/carpediemtal/weibo-image-bed/tree/master

参考资料

如何在IDEA里运行javafx:

https://openjfx.io/openjfx-docs/