我正在使用以下 groovy 脚本对某些文件集(比如 Java 文件)进行更改,在这里我想在文件中添加包(如果还没有的话)并且下面的代码可以完成这项工作(在这里可以随意提出优化建议)但是它更新该文件中的换行符,这是我宁愿避免的,有什么建议吗?
void addIfRequired(def directory, def filePath) {
def inputFile = new File(filePath)
boolean containsPackage = false;
List<String> lines = inputFile.readLines();
for (def eachLine : lines) {
eachLine = eachLine.trim();
if (eachLine.startsWith("package ")) {
containsPackage = true
break
} else if (eachLine.startsWith("import ")) {
// Stop looking if we don't get package till import statement.
break;
}
}
if (!containsPackage) {
String lineSeparator = System.getProperty("line.separator");
// The following API generates the package name
def packageN = getPackage(inputFile, directory)
boolean packageAdded = false;
StringBuilder outputTxt = new StringBuilder();
for (def line : lines) {
if (!packageAdded && line.startsWith("import ")) {
outputTxt.append("package " + packageN + ";" + lineSeparator)
packageAdded = true;
}
outputTxt.append(line);
outputTxt.append(lineSeparator);
}
inputFile.write(outputTxt.toString());
}
}