groovy学习(二)
groovy学习(二)
背景描述:
groovy
简单学习了下,准备应用。正好有个简单的需求用groovy
来练练:
markdown
文档插入图片使用
使用的本地文件,这只是一个临时的做法,最终要把图片全部转为base64编码插入到文档中,这样就可以摆脱文档环境的依赖。
实现这个过程很简单:遍历文档,正则匹配并修改特定语法,文档末尾追加base64字符串。正好这个脚本涉及到了:流程控制、方法、IO、正则等许多基础语法,非常适合训练。
这个文章就是用以下脚本转换的
1.代码
package main
class GenMD {
static def pictureList = [];
static def targetFile = new File('E:/chen/', 'jenins.md')
static def getAvator(filePath){
def regex = /^!\[avator\].*\)$/;
def avatorCount =1;
new File(filePath).eachLine{
line -> {
if(line.matches(regex)){
pictureList.add(line);
targetFile.append("![image][link${avatorCount}]")
targetFile.append('\n')
avatorCount++;
}else {
targetFile.append(line)
targetFile.append('\n')
}
}
}
}
static def getFileList(filePath){
getAvator(filePath)
pictureList.eachWithIndex{
def it, int index -> {
String a = it.replaceAll("!\\[avator\\]","")
a = a.replaceAll("\\(","")
a = a.replaceAll("\\)","")
def base64 = "[link${index + 1}]: data:image/png;base64," + toBase64(a);
targetFile.append(base64)
targetFile.append('\n')
}
}
return null;
}
static def toBase64(filePath){
def encodedText = new File(filePath).readBytes().encodeBase64().toString() ;
return encodedText;
}
static void main(String[] args) {
getFileList("E:/学习/博客/jenkins.md")
}
}
2.base64编码
中间有一段时间图片总是无法正常加载,查了好久才发现原因:使用的编码工具有问题。
3.待解决问题
之前的代码我是直接用notePad++
写的,再编译执行。准备进一步研究groovy
,就在Eclipse上安装groovy
插件(非常需要高亮、自动补齐、编译检查等功能)。结果安装之后打开这个代码编译报错,猜测是版本的问题,待解决。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步