在Groovy中文件的操作和替换非常简单,使用如下语句即可瞬间替换文件内容:
File testFile = new File(project.getProjectDir(),
"/src/main/Test.java".replace("/", File.separator))
println("==================")
println(testFile.getAbsolutePath())
println testFile.getText("utf-8")
String after = testFile.getText("utf-8").replaceAll("def\\{abc.delay\\}", "123321")
println after
testFile.write(after)
println "================"
println testFile.getText("utf-8")
逐行替换代码也是很简洁:
new File('c:\\temp\\1.txt').eachLine('UTF-8') {
println "new line->" + it
}
new File('c:\\temp\\1.txt').withReader('UTF-8') { reader ->
reader.eachLine {
println "Another line:" + it
}
}